<?php

/**

 * Created by PhpStorm.

 * User: Administrator

 * Date: 2018/11/19

 * Time: 16:51



 * 订单类

 */



namespace app\console\controller;

use app\console\model\RefundOrderAudit;

use app\console\model\ServiceOrderGoods;

use think\Build;

use think\Controller;

use think\Db;

use think\Request;

use think\Url;

use app\interfaces\controller\Alipay;

use think\Exception;

use think\Session;

use think\Loader;

use app\common\trilateral\Classify as ClassifyAlias;

use think\Cache;

class ServiceOrder extends Controller

{

    protected $beforeActionList = [

        'manage',

//        'second' =>  ['except'=>'hello'],

//        'three'  =>  ['only'=>'hello,data'],

    ];



    public function manage(){



        $manage_array = Db::name('manager')->where('level = 2 and is_allow = 2 or level = 1 or level = 5 and is_allow = 2 ')->column('id');



        $this->assign('manage_array',implode(',',$manage_array));



    }

    /**

     * @return array|mixed|\think\response\View

     * 订单列表

     */

    public function index()

    {



        $param = Request::instance()->param();

        $level = \session('role_id');//当前登录的管理员界别 5 7 8 9 10

        $auding_status = Session::get('auding_status');

        if($auding_status == 1){

            $where['o.shop_id'] = ['eq',\session('shop_id')];

        }

        $where['o.order_type'] = ['eq', 2];

        $where['o.status'] = ['in','50,1,6,5,4,10,11,12,20'];

        if (!empty($param['status'])){

            if($param['status'] == 2){

                $where['o.status'] = ['in', $this->status];

            }else{

                //$where['o.auding_status'] = ['eq',2];

                $where['o.status'] = ['eq', $param['status']];

            }

        }

        if (!empty($param['auding_status'])){

            $where['o.auding_status'] = ['eq', $param['auding_status']];

            $where['o.is_free_order'] = ['eq', 2];

        }

        if (!empty($param['finance_order'])) $where['o.finance_order'] = ['eq', $param['finance_order']];

        if (!empty($param['order_online'])) $where['o.order_online'] = ['eq', $param['order_online']];

        if (!empty($param['shop_id'])) $where['o.shop_id'] = ['eq', $param['shop_id']];

        if (!empty($param['is_certification'])) $where['m.is_certification'] = ['eq', $param['is_certification']];

        if (!empty($param['single_parent_id'])) $where['single_parent_id|single_id'] = ['eq', $param['single_parent_id']];

        if (!empty($param['title'])){

            $where['o.username|o.shop_order_number|o.order_number|o.car_number|m.car_number|se2.cat_name|se.cat_name'] = ['like', '%'.$param['title'].'%'];//|sew.cat_name|sewa.cat_name

        }



        if (!empty($param['interval_timer'])) {

            $interval_timer = explode('/', $param['interval_timer']);

            $where['o.create_time'] = ['between', [$interval_timer[0], $interval_timer[1]]];

        }

        if(session('role_id') != 1){

            $where['o.is_delete'] = ['eq', 1];

        }



        $data = \app\console\model\Order::alias('o')

            ->join('member m', 'o.member_id = m.id','left')

            ->join('single se','o.single_parent_id = se.id','left')

            ->join('single se2','o.single_id = se2.id','left')

            ->join('shop s', 'o.shop_id = s.id','left')



//            ->join('single sew','sar.single_id = sew.id','left')

//            ->join('single sewa','sar.assignor_content = sewa.id','left')

//            ->join('shop_assignor_records sar','o.id = sar.order_id','left')

            ->field('m.username,m.car_number m_car_number,m.is_certification,o.*,s.shop_title,se.cat_name')

            ->order('o.id','desc')

            ->where($where)

            ->group('o.id')

            ->paginate(10, false, ['query' => $param])->each(function($item,$key) use ($level){

                if(session('role_id') != 1){

                    $item->username = hideStr($item->username,1,6);

                }

                $item->cat_one = Db::name('single')->where('id',$item['single_id'])->value('cat_name');

                if($item['status'] == 12 || $item['status'] == 10 || $item['status'] == 11){

                   $item->refund_create_time = Db::name('order_refund')->where('order_id',$item['id'])->value('create_time');



                }

                if($item->is_certification == 2 && !empty($item->car_number)){

                    //$item->car_number = '('.$item->car_number.')';

                }

                $item->refund_button = false;

                $count = (new RefundOrderAudit())->where('order_id',$item->id)->where('status','11')->count();

                if($level == 5){

                    if($count == 0){

                        $item->refund_button = true;

                    }

                }

                if($level == 7){

                    if($count == 1){

                        $item->refund_button = true;

                    }

                }

                if($level == 8){

                    if($count == 2){

                        $item->refund_button = true;

                    }

                }

                if($level == 9){

                    if($count == 3){

                        $item->refund_button = true;

                    }

                }

                if($level == 10){

                    if($count == 4){

                        $item->refund_button = true;

                    }

                }

            });



        $total_count = Db::name('order o')

            ->join('member m', 'o.member_id = m.id','left')

            ->join('single se','o.single_parent_id = se.id','left')

            ->join('single se2','o.single_id = se2.id','left')

            ->join('shop s', 'o.shop_id = s.id','left')



//            ->join('shop_assignor_records sar','o.id = sar.order_id','left')

//            ->join('single sew','sar.single_id = sew.id','left')

//            ->join('single sewa','sar.assignor_content = sewa.id','left')

            ->field('m.car_number m_car_number,m.is_certification,o.*,se.cat_name')



            ->order('o.id','desc')

            ->where($where)

            ->group('o.id')

            ->count();



        $total_price = Db::name('order o')

            ->join('member m', 'o.member_id = m.id','left')

            ->join('single se','o.single_parent_id = se.id','left')

            ->join('single se2','o.single_id = se2.id','left')

            ->join('shop s', 'o.shop_id = s.id','left')

//            ->join('shop_assignor_records sar','o.id = sar.order_id','left')

//            ->join('single sew','sar.single_id = sew.id','left')

//            ->join('single sewa','sar.assignor_content = sewa.id','left')

            ->field('m.car_number m_car_number,m.is_certification,o.*,se.cat_name')

            ->order('o.id','desc')

            ->where($where)

            ->sum('amount');

        $shop_list = Db::name('shop s')->field('id,shop_title')->select();



        $sj_total_price = Db::name('order o')

            ->join('member m', 'o.member_id = m.id','left')

            ->join('single se','o.single_parent_id = se.id','left')

            ->join('single se2','o.single_id = se2.id','left')

            ->join('shop s', 'o.shop_id = s.id','left')

//            ->join('shop_assignor_records sar','o.id = sar.order_id')

//            ->join('single sew','sar.single_id = sew.id')

//            ->join('single sewa','sar.assignor_content = sewa.id')

            ->field('m.car_number m_car_number,m.is_certification,o.*,se.cat_name')

            ->order('o.id','desc')

            ->where($where)

            ->sum('sj');



        $fenlie = Db::name('single')->where('parent_id',0)->where(' is_delete = 1')->order(['sort' => 'asc','id' => 'asc'])->select()->toArray();

        foreach ($fenlie as &$v){

            $v['son'] = Db::name('single')->where('parent_id',$v['id'])->where(' is_delete = 1')->order(['sort' => 'asc','id' => 'asc'])->select();

        }

//        halt($fenlie);

        return view('', ['data' => $data,

            'shop_list' => $shop_list,

            'fenlei' => $fenlie,

            'total_count' => $total_count,

            'total_price' => $total_price,

            'sj_total_price' => $sj_total_price,

        ]);

    }



    public function table(){

        return view();

    }



    /**

     * 公共订单导出

     */

    public function excel(){



        $param = Request::instance()->param();



        $auding_status = Session::get('auding_status');

        $where = [];

        if($auding_status == 1){

            $where['shop_id'] = ['eq',\session('shop_id')];

        }

        //$where['o.order_type'] = ['eq', 2];



        if (!empty($param['status'])){

            if($param['status'] == 2){

                $where['o.status'] = ['in', $this->status];

            }else{

                $where['o.status'] = ['eq', $param['status']];

            }

        }else{

//            if ($param['order_type']==3){

//                $where['o.status'] = ['in','1,6,5,4,10,11,12,20'];

//            }

        }

       // if (!empty($param['status'])) $where['o.status'] = ['eq', $param['status']];

        if (!empty($param['auding_status'])){

            $where['o.auding_status'] = ['eq', $param['auding_status']];

            $where['o.is_free_order'] = ['eq', 2];

        }

        if (!empty($param['is_certification'])) $where['m.is_certification'] = ['eq', $param['is_certification']];

        if (!empty($param['shop_id'])){

            $where['shop_id'] = ['eq', $param['shop_id']];

            //$where['m.shop_invite_id|o.shop_id'] = ['eq', $param['shop_id']];

        }

        if (!empty($param['order_type'])) $where['order_type'] = ['eq', $param['order_type']];

        if (!empty($param['single_parent_id'])) $where['single_parent_id'] = ['eq', $param['single_parent_id']];

        if (!empty($param['title'])) $where['o.username|o.shop_order_number|o.order_number|m.car_number'] = ['like', '%'.$param['title'].'%'];



        if (!empty($param['interval_timer'])) {

            $interval_timer = explode('/', $param['interval_timer']);

            $where['o.create_time'] = ['between', [$interval_timer[0], $interval_timer[1]]];

        }



//        halt($where);

        $data = \app\console\model\Order::alias('o')

            ->join('member m', 'o.member_id = m.id','left')

            ->join('single se','o.single_parent_id = se.id','left')

            ->join('shop s', 'o.shop_id = s.id','left')

           // ->field('m.username,m.car_number,m.is_certification,o.*,s.shop_title,se.cat_name')

            ->order('id','desc')

            ->field('o.*,m.username,m.is_certification,s.shop_title,se.cat_name')

            ->order('id','desc')

            ->where($where)

            ->paginate(1000000, false, $param)->each(function($item,$key){

                $item->m_car_number = (new \app\index\controller\GiftOrder())->car_number('',$item->member_id);

                if(session('role_id') != 1){

                    $item->username = hideStr($item->username,1,6);

                }

                if($item->is_certification == 2 && !empty($item->car_number)){

                    //$item->car_number = '('.$item->car_number.')';

                }

                if($item->is_certification == 1){

                    $item->is_certification_text = '未认证';

                }

                if($item->is_certification == 3){

                    $item->is_certification_text = '等待认证';

                }

                if($item->is_certification == 2){

                    $item->is_certification_text = '已认证';

                }

                $item->cat_one = Db::name('single')->where('id',$item['single_id'])->value('cat_name');



                if($item->shop_id == 0 ){

                    $shop_title = '目前还没有指定门店';

                }else{

                    $shop_title = $item->shop_title;

                }

                $item->shop_title = $shop_title;



                switch ($item->status){

                    case 50;

                    $item->status = '等待沟通';

                    case 20;

                        $item->status = '已取消'.'('.$item->cancel_content.')';

                        break;

                    break;

                    case 1;

                    $item->status = '代付款';

                    break;

                    case 2;

                    $item->status = '代发货';

                    break;

                    case 3;

                    $item->status = '已发货';

                    break;

                    case 4;

                    $item->status = '已完成';

                    break;

                    case 6;

                    $item->status = '进行中';

                    break;

                    case 5;

                        if($item->order_type == 1){

                            $item->status = '待评价';

                        }

                        if($item->order_type == 2){

                            $item->status = '已确认';

                        }

                        if($item->order_type == 3){

                            $item->status = '待评价';

                        }

                        if($item->order_type == '已确认'){

                            $item->status = '1';

                        }

                        break;

                    case 10;

                        $item->status = '退款中';

                        break;

                    case 11;

                        $item->status = '退款成功';

                        break;

                    case 12;

                        $item->status = '退款失败';

                    break;



                }

                $item['content'] = '';

                switch ($item['order_type']){

                    case 1;

                        //$item->order_number = $item->shop_order_number;

                        $goods_list = Db::name('order_goods')->alias('og')->join('shop_goods g','og.goods_id = g.id')->field('og.id,og.goods_id,og.title,og.price,og.number,og.attribute,g.thumb_img')->where('order_id',$item['id'])->select();

                        $str = '';

                        if(!empty($goods_list)){

                            foreach ($goods_list as $k => $v){

                                $str .=

                                    '标题:'.$v['title'].' '.

                                    '价钱:'.$v['price'].' '.

                                    '数量:'.$v['number'].' ';

                            }

                        }

                        $item['content'] = $str;

                        break;

                    case 2;





                        switch ($item['service_type_id']){

                            case 1;

                                $data = Db::name('order_service os')->join('order o','o.id = os.order_id')->join('single s','o.single_id = s.id','left')->field('s.pic_url,os.*,phone,protecteder,protecter_back,car_face,car_back')->where('os.order_id',$item['id'])->select()->toArray();

                                $data[0]['single_title'] = Db::name('single')->where('id',$item['single_id'])->value('cat_name');

                                $data[0]['single_parent_title'] = Db::name('single')->where('id',$item['single_parent_id'])->value('cat_name');

                                $str = '';

                                foreach (explode(',',$data[0]['type_id_str']) as $k => $v){

                                    $str .= Db::name('protect_type')->where('id',$v)->value('title').' ';

                                }

                                $data[0]['str'] = $str;

                                $data_str = '姓名:'.    $data[0]['protecteder'].' '.

                                            '手机号码:'. $data[0]['phone'].' '.

                                            '车主姓名:'. $data[0]['plat_name'].' '.

                                    '车牌号码:'. $data[0]['plat_number'].' '.

                                    '车辆识别码:'. $data[0]['plat_code'].' '.

                                    '发动机号:'. $data[0]['engine_number'].' '.

                                    '注册日期:'. $data[0]['register_time'].' '.

                                    '投保险种:'. $str;

                                $item['content'] = $data_str;

                                break;

                            case 2;

                                $data = Db::name('order_service os')->join('order o','o.id = os.order_id')->join('single s','o.single_id = s.id','left')->field('s.pic_url,os.*,phone,protecteder,protecter_back,car_face,car_back')->where('os.order_id',$item['id'])->select()->toArray();

                                $data[0]['single_title'] = Db::name('single')->where('id',$item['single_id'])->value('cat_name');

                                $data[0]['single_parent_title'] = Db::name('single')->where('id',$item['single_parent_id'])->value('cat_name');

                                $str = '';

                                foreach (explode(',',$data[0]['type_id_str']) as $k => $v){

                                    $str .= Db::name('protect_type')->where('id',$v)->value('title').' ';

                                }



                                $data[0]['str'] = $str;

                                $data_str = '姓名:'.    $data[0]['protecteder'].' '.

                                    '手机号码:'. $data[0]['phone'].' '.

                                    '车主姓名:'. $data[0]['plat_name'].' '.

                                    '车牌号码:'. $data[0]['plat_number'].' '.

                                    '车辆识别码:'. $data[0]['plat_code'].' '.

                                    '发动机号:'. $data[0]['engine_number'].' '.

                                    '注册日期:'. $data[0]['register_time'];

                                $item['content'] = $data_str;

                                break;

                            case 3;

                                if($item->single_id == 11){



                                }

                                $item['content'] = '';

                                break;

                            case 4;

                                $data = Db::name('order_service os')->join('order o','o.id = os.order_id')->join('single s','o.single_id = s.id','left')->field('s.pic_url,os.type_id_str,phone,protecteder,protecter_back,car_face,car_back')->where('os.order_id',$item['id'])->select()->toArray();

                                $data[0]['single_title'] = Db::name('single')->where('id',$item['single_id'])->value('cat_name');

                                $data[0]['single_parent_title'] = Db::name('single')->where('id',$item['single_parent_id'])->value('cat_name');

                                $data[0]['pic_url'] = Db::name('single')->where('id',$item['single_id'])->value('pic_url');

                                $data[0]['phone'] = '';

                                $data[0]['protecteder'] = '';

                                $data[0]['protecter_back'] = '';

                                $data[0]['car_face'] = '';

                                $data[0]['car_back'] = '';

                                $data[0]['type_id_str'] = '';

                                $item['content'] = '';

                                break;

                        }

                        break;

                    case 3;

                        //$item->shop_title = '礼包订单';

                        $gift = Db::name('order o')->join('gift g','o.gift_id = g.id')->field('g.id,g.single_pic,o.gift_title,o.gift_describe,o.sale_price,o.gift_number')->where('o.id',$item['id'])->find();

                        $item['content'] =

                            '礼包名称:'.$item->gift_title.' '.

                            '售卖价格:'.$item->sale_price.' '.

                            '礼包原价:'.$item->gift_origin_price.' '.

                            '促销开始时间:'.$item->gift_start_time.' '.

                            '促销结束时间:'.$item->gift_end_time.' ';

                        ;

                        break;

                }

                if($item['status'] == 12 || $item['status'] == 10 || $item['status'] == 11){

                    $item->refund_create_time = Db::name('order_refund')->where('order_id',$item['id'])->value('create_time');

                }else{

                    $item->refund_create_time = '';

                }

            });



        $this->push($data,'订单导出');



    }



    public function service_excel(){



        $param = Request::instance()->param();

        $auding_status = Session::get('auding_status');

        if($auding_status == 1){

            $where['shop_id'] = ['eq',\session('shop_id')];

        }

        //$where['o.order_type'] = ['eq', 2];



        if (!empty($param['status'])){

            if($param['status'] == 2){

                $where['o.status'] = ['in', $this->status];

            }else{

                $where['o.status'] = ['eq', $param['status']];

            }

        }

        // if (!empty($param['status'])) $where['o.status'] = ['eq', $param['status']];

        if (!empty($param['is_certification'])) $where['m.is_certification'] = ['eq', $param['is_certification']];

        if (!empty($param['shop_id'])) $where['shop_id'] = ['eq', $param['shop_id']];

        if (!empty($param['order_type'])) $where['order_type'] = ['eq', $param['order_type']];

        if (!empty($param['single_parent_id'])) $where['single_parent_id'] = ['eq', $param['single_parent_id']];

        if (!empty($param['title'])) $where['o.username|o.shop_order_number|o.order_number|m.car_number'] = ['like', '%'.$param['title'].'%'];

        if (!empty($param['interval_timer'])) {

            $interval_timer = explode('/', $param['interval_timer']);

            $where['o.create_time'] = ['between', [$interval_timer[0], $interval_timer[1]]];

        }



        $data = \app\console\model\Order::alias('o')

            ->join('member m', 'o.member_id = m.id','left')

            ->join('single se','o.single_parent_id = se.id','left')

            ->join('shop s', 'o.shop_id = s.id','left')

//            ->field('m.username,m.car_number,m.is_certification,o.*,s.shop_title,se.cat_name')

            ->order('id','desc')

            ->field('o.*,m.username,m.car_number,m.is_certification,s.shop_title,se.cat_name')

            ->order('id','desc')

            ->where($where)

            ->paginate(10000, false, $param)->each(function($item,$key){

                if(session('role_id') != 1){

                    $item->username = hideStr($item->username,1,6);

                }

                if($item->is_certification == 2 && !empty($item->car_number)){

                    //$item->car_number = '('.$item->car_number.')';

                }

                if($item->is_certification == 1){

                    $item->is_certification_text = '未认证';

                }

                if($item->is_certification == 3){

                    $item->is_certification_text = '等待认证';

                }

                if($item->is_certification == 2){

                    $item->is_certification_text = '已认证';

                }

                $item->cat_one = Db::name('single')->where('id',$item['single_id'])->value('cat_name');

                switch ($item->status){

                    case 50;

                        $item->status = '等待沟通';

                    case 20;

                        $item->status = '已取消'.'('.$item->cancel_content.')';

                        break;

                        break;

                    case 1;

                        $item->status = '代付款';

                        break;

                    case 2;

                        $item->status = '代发货';

                        break;

                    case 3;

                        $item->status = '已发货';

                        break;

                    case 4;

                        $item->status = '已完成';

                        break;

                    case 6;

                        $item->status = '进行中';

                        break;

                    case 5;

                        if($item->order_type == 1){

                            $item->status = '待22评价';

                        }

                        if($item->order_type == 2){

                            $item->status = '已确认';

                        }

                        if($item->order_type == 3){

                            $item->status = '1';

                        }



                        break;

                    case 10;

                        $item->status = '退款中';

                        break;

                    case 11;

                        $item->status = '退款成功';

                        break;

                    case 12;

                        $item->status = '退款失败';

                        break;



                }

                $item['content'] = '';

                switch ($item['order_type']){

                    case 1;

                        //$item->order_number = $item->shop_order_number;

                        $goods_list = Db::name('order_goods')->alias('og')->join('shop_goods g','og.goods_id = g.id')->field('og.id,og.goods_id,og.title,og.price,og.number,og.attribute,g.thumb_img')->where('order_id',$item['id'])->select();

                        $str = '';

                        if(!empty($goods_list)){

                            foreach ($goods_list as $k => $v){

                                $str .=

                                    '标题:'.$v['title'].' '.

                                    '价钱:'.$v['price'].' '.

                                    '数量:'.$v['number'].' ';

                            }

                        }

                        $item['content'] = $str;

                        break;

                    case 2;

                        if($item->shop_id == 0 ){

                            $shop_title = '目前还没有指定门店';

                        }else{

                            $shop_title = $item->shop_title;

                        }

                        $item->shop_title = $shop_title;



                        switch ($item['service_type_id']){

                            case 1;

                                $data = Db::name('order_service os')->join('order o','o.id = os.order_id')->join('single s','o.single_id = s.id','left')->field('s.pic_url,os.*,phone,protecteder,protecter_back,car_face,car_back')->where('os.order_id',$item['id'])->select()->toArray();

                                $data[0]['single_title'] = Db::name('single')->where('id',$item['single_id'])->value('cat_name');

                                $data[0]['single_parent_title'] = Db::name('single')->where('id',$item['single_parent_id'])->value('cat_name');

                                $str = '';

                                foreach (explode(',',$data[0]['type_id_str']) as $k => $v){

                                    $str .= Db::name('protect_type')->where('id',$v)->value('title').' ';

                                }

                                $data[0]['str'] = $str;

                                $data_str = '姓名:'.    $data[0]['protecteder'].' '.

                                    '手机号码:'. $data[0]['phone'].' '.

                                    '车主姓名:'. $data[0]['plat_name'].' '.

                                    '车牌号码:'. $data[0]['plat_number'].' '.

                                    '车辆识别码:'. $data[0]['plat_code'].' '.

                                    '发动机号:'. $data[0]['engine_number'].' '.

                                    '注册日期:'. $data[0]['register_time'].' '.

                                    '投保险种:'. $str;

                                $item['content'] = $data_str;

                                break;

                            case 2;

                                $data = Db::name('order_service os')->join('order o','o.id = os.order_id')->join('single s','o.single_id = s.id','left')->field('s.pic_url,os.*,phone,protecteder,protecter_back,car_face,car_back')->where('os.order_id',$item['id'])->select()->toArray();

                                $data[0]['single_title'] = Db::name('single')->where('id',$item['single_id'])->value('cat_name');

                                $data[0]['single_parent_title'] = Db::name('single')->where('id',$item['single_parent_id'])->value('cat_name');

                                $str = '';

                                foreach (explode(',',$data[0]['type_id_str']) as $k => $v){

                                    $str .= Db::name('protect_type')->where('id',$v)->value('title').' ';

                                }



                                $data[0]['str'] = $str;

                                $data_str = '姓名:'.    $data[0]['protecteder'].' '.

                                    '手机号码:'. $data[0]['phone'].' '.

                                    '车主姓名:'. $data[0]['plat_name'].' '.

                                    '车牌号码:'. $data[0]['plat_number'].' '.

                                    '车辆识别码:'. $data[0]['plat_code'].' '.

                                    '发动机号:'. $data[0]['engine_number'].' '.

                                    '注册日期:'. $data[0]['register_time'];

                                $item['content'] = $data_str;

                                break;

                            case 3;

                                if($item->single_id == 11){



                                }

                                $item['content'] = '';

                                break;

                            case 4;

                                $data = Db::name('order_service os')->join('order o','o.id = os.order_id')->join('single s','o.single_id = s.id','left')->field('s.pic_url,os.type_id_str,phone,protecteder,protecter_back,car_face,car_back')->where('os.order_id',$item['id'])->select()->toArray();

                                $data[0]['single_title'] = Db::name('single')->where('id',$item['single_id'])->value('cat_name');

                                $data[0]['single_parent_title'] = Db::name('single')->where('id',$item['single_parent_id'])->value('cat_name');

                                $data[0]['pic_url'] = Db::name('single')->where('id',$item['single_id'])->value('pic_url');

                                $data[0]['phone'] = '';

                                $data[0]['protecteder'] = '';

                                $data[0]['protecter_back'] = '';

                                $data[0]['car_face'] = '';

                                $data[0]['car_back'] = '';

                                $data[0]['type_id_str'] = '';

                                $item['content'] = '';

                                break;

                        }

                        break;

                    case 3;

                        $item->shop_title = '礼包订单';

                        $gift = Db::name('order o')->join('gift g','o.gift_id = g.id')->field('g.id,g.single_pic,o.gift_title,o.gift_describe,o.sale_price,o.gift_number')->where('o.id',$item['id'])->find();

                        $item['content'] =

                            '礼包名称:'.$item->gift_title.' '.

                            '售卖价格:'.$item->sale_price.' '.

                            '礼包原价:'.$item->gift_origin_price.' '.

                            '促销开始时间:'.$item->gift_start_time.' '.

                            '促销结束时间:'.$item->gift_end_time.' ';

                        ;

                        break;

                }

                if($item['status'] == 12 || $item['status'] == 10 || $item['status'] == 11){

                    $item->refund_create_time = Db::name('order_refund')->where('order_id',$item['id'])->value('create_time');

                }else{

                    $item->refund_create_time = '';

                }

            });



        $this->push($data,'订单导出');



    }







    public function push($data, $name = 'Excel')

    {



        set_time_limit(0);



        ini_set('memory_limit', '1024M');



        error_reporting(E_ALL);



        date_default_timezone_set('Asia/Shanghai');







        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');



        $objPHPExcel = new \PHPExcel();







        /*以下是一些设置 ，什么作者  标题啊之类的*/



        $objPHPExcel->getProperties()->setCreator("管理员")



            ->setLastModifiedBy("管理员")



            ->setTitle("电话本导出")



            ->setSubject("数据EXCEL导出")



            ->setDescription("备份数据")



            ->setKeywords("excel")



            ->setCategory("result file");



        $objPHPExcel->setActiveSheetIndex(0)



            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推



            ->setCellValue('A1', '订单号')

            ->setCellValue('B1', '一级分类')

            ->setCellValue('C1', '二级分类')

            ->setCellValue('D1', '买家账号')

            ->setCellValue('E1', '会员车牌号')

            ->setCellValue('F1', '订单车牌号')

            ->setCellValue('G1', '是否认证')

            ->setCellValue('H1', '下单/退款时间')

            ->setCellValue('I1', '消费门店')

            ->setCellValue('J1', '订单总额')

            ->setCellValue('K1', '订单状态')

            ->setCellValue('L1', '创建时间')

            ->setCellValue('M1', '订单详情')

        ;



        $sheet1 = [];





        for ($x = 0; $x < count($sheet1); $x++) {



            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(



                array(



                    'font'      => array(



                        'bold' => true



                    ),



                    'alignment' => array(



                        'horizontal' =>



                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER



                    )



                )



            );



        }







        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/







        $n = 0;



        foreach ($data as $v) {



            $num = $n + 2;

            $objPHPExcel->setActiveSheetIndex(0)



                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推

                ->setCellValue('A' . $num, $v['order_number'])

                ->setCellValue('B' . $num, $v['cat_name'])

                ->setCellValue('C' . $num, $v['cat_one'])

                ->setCellValue('D' . $num, "\t".$v['username']."\t")

                ->setCellValue('E' . $num, $v['m_car_number'])

                ->setCellValue('F' . $num, $v['car_number'])

                ->setCellValue('G' . $num, $v['is_certification_text'])

                ->setCellValue('H' . $num, $v['create_time'].'/'.$v['refund_create_time'])

                ->setCellValue('I' . $num, $v['shop_title'])

                ->setCellValue('J' . $num, $v['amount'])

                ->setCellValue('K' . $num, $v['status'])

                ->setCellValue('L' . $num, $v['create_time'])

                ->setCellValue('M' . $num, $v['content'])

            ;



            $n++;



        }







        $objPHPExcel->getActiveSheet(0)->setTitle('订单信息导出');

        $objPHPExcel->setActiveSheetIndex(0);







        ob_end_clean();



        header('Content-Type: application/vnd.ms-excel');



        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xls"');



        header('Cache-Control: max-age=0');



        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');



        $objWriter->save('php://output');

        exit;

    }



    /**

     * @param $id

     * 订单修改

     */

    public function update()

    {



        $auding_status = Session::get('auding_status');

        $level = \session('role_id');//当前登录的管理员界别 5 7 8 9 10

        $number = db('config')->where('varname', 'web_number')->value('varvalue');

        $id = Request::instance()->param('id', '');

        $where_id = [];

        if ($id) {

            $where_id['o.id'] = ['eq', $id];

            if ($auding_status == 2) {

                Db::name('order o')->where($where_id)->setField('is_read', 1);

            } else {

                Db::name('order o')->where($where_id)->setField('is_read_shop', 1);

            }

        }

        $where_code = [];



        $param = Request::instance()->param();



        if (isset($param['code'])) {

            $date = date('Y-m-d H:i:s', time() - 300);

            $where_code['o.code'] = ['eq', 2];

            $where_code['o.status'] = ['eq', 6];

            $where_code['o.code_time'] = ['egt', $date];

        }

        $service_order = Db::name('order o')->where($where_id)->where($where_code)->find();

        $refund = Db::name('order_refund ors')->field('ors.*,rr.title')->where('order_id', $service_order['id'])->join('refund_reason rr', 'ors.reason_id = rr.id')->find();

        if (Request::instance()->isPost()) {

            $car_number = Request::instance()->post('car_number');

            if(isset($car_number) && empty($car_number)){

                fail('必须填写车牌号');

            }



            $shop_name = Db::name('shop')->where('id', $service_order['shop_id'])->value('shop_title');

            if ($service_order['single_id'] != 11) { //非轮胎寄存包含汽车保险类

                if($service_order['status'] == 50){

                    if ($param['amount'] <= 0) {

                        fail('请填写正确派单金额');

                    }

                    if ($param['shop_id'] <= 0) {

                        fail('请填写派单门店');

                    }

                    if ($param['freight'] > 0) { //商家配送

                        $ret = Db::name('order')->alias('o')

                            ->fetchSql(false)

                            ->where($where_id)

                            ->update([

                                'shop_id' => $param['shop_id'],

                                'amount' => $param['amount'] + $param['freight']+$param['sj'],

                                'order_price' => $param['amount'],

                                'freight' => $param['freight'],

                                'sj' => $param['sj'],

                                'status' => 1, 'shipping' => 1,

                                'is_read_shop' =>0,

                                'explain' => $param['explain'],

                                'shipping_province' => $param['shipping_province'],

                                'shipping_address' => $param['shipping_address'],

                                'shipping_phone' => $param['shipping_phone'],

                                'shipping_name' => $param['shipping_name'],

                                'yuyue_start_time' => $param['yuyue_start_time'],

                                'yuyue_end_time' => $param['yuyue_end_time']

                            ]);



                    } else { //门店自提

                        $ret = Db::name('order')->alias('o')->fetchSql(false)->where($where_id)->update(

                            [   'shop_id' => $param['shop_id'],

                                'amount' => $param['amount']+$param['sj'],

                                'order_price' => $param['amount'],

                                'sj' => $param['sj'],

                                'status' => 1, 'shipping' => 2,

                                'is_read_shop' => 0,

                                'explain' => $param['explain'],

                                'shipping_province' => '',

                                'shipping_address' => '',

                                'shipping_phone' => '',

                                'shipping_name' => '',

                                'yuyue_start_time' => $param['yuyue_start_time'],

                                'yuyue_end_time' => $param['yuyue_end_time']

                            ]);

                    }

                    if ($ret) {

                        Db::name('member_message')->insert(

                            ['member_id' => $service_order['member_id'],

                                'order_number' => $service_order['order_number'],

                                'type_id' => 2,

                                'title' => '您的订单金额及门店已确认,请支付',

                                'content' => $service_order['order_number'],

                                'is_click' => 1,

                                'create_time' => date('Y-m-d H:i:s', time())

                            ]);



                        (new \app\index\controller\MemberMessage())->jpushMessage($service_order['member_id'], '您的订单金额及门店已确认,请支付', '订单金额:' . ($param['amount'] + $param['freight']) . '元,运费:' . $param['freight'] . '元', 2);

                        wingo('订单金额及门店指派完毕', Url::build('index'));

                    }

                }

                //非轮胎寄存

            }else{

                //轮胎寄存

                if($service_order['status'] == 50){

                    $t = explode('/',Request::instance()->param()['interval_timer']);

                    if(empty(Request::instance()->param()['interval_timer'])){

                        $t[0] = $t[1] = '';

                    }

                    if ($param['shop_id'] <= 0) {

                        fail('请指派有效门店');

                    }



                    if ($param['amount'] > 0) {



                        $ret = Db::name('order o')->where('id', $id)->update(['shop_id' => $param['shop_id'], 'amount' => $param['amount'], 'order_price' => $param['amount'], 'status' => 1,'is_read_shop' =>0,'start_time' => $t[0],'end_time' => $t[1],'multi_pic' => serialize(Request::instance()->param('picArr/a')),]);

                        if ($ret !== false) {

                            $hah = Db::name('member_message')->where('order_number', $service_order['order_number'])->update(

                                [

                                    'title' => '您的服务订单(轮胎寄存)已指派门店,请立即支付',

                                    'content' => $service_order['order_number'],

                                    'is_click' => 1,

                                    'create_time' => date('Y-m-d H:i:s', time())

                                ]);



                            $shop_name = Db::name('shop')->where('id', $service_order['shop_id'])->value('shop_title');

                            (new \app\index\controller\MemberMessage())->jpushMessage($service_order['member_id'], '您的服务订单(轮胎寄存)已指派门店,请立即支付', '寄存门店:' . $shop_name . ' 寄存金额为:' . $param['amount'] . '元', 2);

                            wingo('门店指派完毕(付费)', Url::build('index'));

                        }

                    } else {

                        $ret = Db::name('order o')->where('id', $id)->update(['shop_id' => $param['shop_id'],'amount' => 0, 'order_price' => 0, 'status' => 6,'is_read_shop' =>0,'start_time' => $t[0],'end_time' => $t[1],'multi_pic' => serialize(Request::instance()->param('picArr/a')),]);//免费寄存

                        if ($ret !== false) {

                            $hah = Db::name('member_message')->where('order_number', $service_order['order_number'])->update(

                                [

                                    'title' => '您的服务订单(轮胎寄存)已指派门店,请立即支付',

                                    'content' => $service_order['order_number'],

                                    'is_click' => 1,

                                    'create_time' => date('Y-m-d H:i:s', time())

                                ]);





                            (new \app\index\controller\MemberMessage())->jpushMessage($service_order['member_id'], '您的服务订单(轮胎寄存)已指派门店,请立即支付', '寄存门店:' . $shop_name . ' 免费寄存', 2);

                            wingo('门店指派完毕(免费)', Url::build('index'));

                        }

                    }



                    //第一次下单50状态

                }else{

                    if (!empty($param['assignor_id'])) {

//                                $single_id = explode('-',$param['single_id'][0])[0];//门店服务分类 第一个类就代表所有相同的服务类了

//                                $single_title = Db::name('single')->where('id',$single_id)->value('cat_name');//服务类型

//                                $assignor_price = explode('-',$param['single_id'][0])[1];//门店金额

                        // 一对多添加数组

                        // 一对多添加数组



                        $shop_assignor_records = [];

                        for ($i = 0; $i < count($param['assignor_id']); $i++) {

                            $shop_assignor_records[$i]['order_id'] = $service_order['id'];

                            $shop_assignor_records[$i]['assignor_id'] = $param['assignor_id'][$i];

                            $shop_assignor_records[$i]['assignor_price'] = $param['assignor_price'][$i];

                            $shop_assignor_records[$i]['single_id'] = $param['single_id'][$i];

                            $shop_assignor_records[$i]['type'] = $param['typea'][$i];

                            $shop_assignor_records[$i]['assignor_content'] = $param['assignor_content'][$i];

                            $shop_assignor_records[$i]['create_time'] = date('Y-m-d H:i:s', time());

                            $shop_assignor_records[$i]['shop_id'] = $service_order['shop_id'];

                            $shop_assignor_records[$i]['order_type'] = 2;

                            $shop_assignor_records[$i]['is_agree'] = 2;

//                                    Db::name('shop_assignor_records')->insert(

//                                        ['assignor_id' => $param['assignor_id'][$i],

//                                         'assignor_price' => $param['assignor_price'][$i],

//                                         'order_id' => $service_order['id'],

//                                         'order_type' => $service_order['order_type'],

//                                         'order_type' => $service_order['order_type'],

//                                         'create_time' => date('Y-m-d H:i:s',time()),

//                                         'shop_id' => \session('shop_id')

//                                        ]);

                        }

                        Db::name('shop_assignor_records')->insertAll($shop_assignor_records);



                        win('人员添加完毕(轮胎)', Url::build('index'));





                    }



                    //如果门店一致,并且没有添加人员



                }



                //$t = explode('/', Request::instance()->param()['interval_timer']);



                if(!empty(Request::instance()->param('picArr/a',''))){



                    Db::name('order o')

                        ->where($where_id)

                        ->where($where_code)

//                        ->where('status', 6)

                        ->update( ['multi_pic' => serialize(Request::instance()->param('picArr/a',''))]);





//                Db::name('order o')

//                    ->where($where_id)

//                    ->where($where_code)

//                    ->where('status', 6)

//                    ->update(['start_time' => $t[0], 'end_time' => $t[1], 'multi_pic' => serialize(Request::instance()->param('picArr/a',''))]);

            }

                //轮胎寄存

            }



            if(in_array($service_order['status'],[1,6])){ //待支付和进行中 重新指派门店

                //任何时候都可以设置预约时间



                $ret = Db::name('order')->alias('o')->fetchSql(false)->where($where_id)->update(

                    [

                        'yuyue_start_time' => $param['yuyue_start_time'],

                        'yuyue_end_time' => $param['yuyue_end_time'],

                        'explain' => $param['explain']

                    ]);

                if(count(Request::instance()->param('picArr/a')) > 2){

//                    fail('图片最多上传2张');

                }

                if (!empty($param['assignor_id']) && count($param['assignor_id']) != count(array_unique($param['assignor_id']))) {

                    //fail('服务人员不能重复');

                }

                if(isset($param['single_id']) && count(array_unique($param['single_id'])) >= 2){

                    //fail('一次只能服务一个分类');

                }

                if($auding_status == 2){ //总后台6状态

                    if ($param['amount'] <= 0) {

                        if($service_order['single_id'] != 11){

                            fail('请填写正确派单金额');

                        }



                    }

                    if ($param['shop_id'] <= 0) {

                        fail('请填写派单门店');

                    }



                    //当前数据和添加的不一致就是修改了

                    if($param['shop_id'] != $service_order['shop_id']){

                        //where('shop_id',$service_order['shop_id'])->

                        Db::name('shop_assignor_records')->where('order_id',$service_order['id'])->delete();

                        $ret = Db::name('order')->alias('o')->fetchSql(false)->where($where_id)->update(

                            ['shop_id' => $param['shop_id'],

                                'is_read_shop' => 0,

                                'multi_pic' => serialize(Request::instance()->param('picArr/a')),

                                'explain' => $param['explain'],

                                'yuyue_start_time' => $param['yuyue_start_time'],

                                'yuyue_end_time' => $param['yuyue_end_time']

                            ]);

                        wingo('重新指派门店完毕', Url::build('index'));



                    }else{

                        //20190828新添加进行中状态

                        if (!empty($param['assignor_id'])) {

//                                $single_id = explode('-',$param['single_id'][0])[0];//门店服务分类 第一个类就代表所有相同的服务类了

//                                $single_title = Db::name('single')->where('id',$single_id)->value('cat_name');//服务类型

//                                $assignor_price = explode('-',$param['single_id'][0])[1];//门店金额

                            // 一对多添加数组

                            // 一对多添加数组

                            $shop_assignor_records = [];

                            for ($i = 0; $i < count($param['assignor_id']); $i++) {

                                $shop_assignor_records[$i]['order_id'] = $service_order['id'];

                                $shop_assignor_records[$i]['assignor_id'] = $param['assignor_id'][$i];

                                $shop_assignor_records[$i]['assignor_price'] = $param['assignor_price'][$i];

                                $shop_assignor_records[$i]['single_id'] = $param['single_id'][$i];

                                $shop_assignor_records[$i]['type'] = $param['typea'][$i];

                                $shop_assignor_records[$i]['assignor_content'] = $param['assignor_content'][$i];

                                $shop_assignor_records[$i]['create_time'] = date('Y-m-d H:i:s', time());

                                $shop_assignor_records[$i]['shop_id'] = $service_order['shop_id'];

                                $shop_assignor_records[$i]['order_type'] = 2;

                                $shop_assignor_records[$i]['is_agree'] = 2;

//                                    Db::name('shop_assignor_records')->insert(

//                                        ['assignor_id' => $param['assignor_id'][$i],

//                                         'assignor_price' => $param['assignor_price'][$i],

//                                         'order_id' => $service_order['id'],

//                                         'order_type' => $service_order['order_type'],

//                                         'order_type' => $service_order['order_type'],

//                                         'create_time' => date('Y-m-d H:i:s',time()),

//                                         'shop_id' => \session('shop_id')

//                                        ]);

                            }

                            Db::name('shop_assignor_records')->insertAll($shop_assignor_records);

                            $last_id = Db::getLastInsID();

                            $single_title = Db::name('single')->where('id', $param['single_id'][0])->value('cat_name');

                            Db::name('member_message')->insert(

                                ['member_id' => $service_order['member_id'],

                                    'order_number' => $last_id,

                                    'type_id' => 4,

                                    'title' => '您的服务服务已使用,请确认',

                                    'content' => $service_order['order_number'],

                                    'is_click' => 1,

                                    'create_time' => date('Y-m-d H:i:s', time())

                                ]);



                            (new \app\index\controller\MemberMessage())->jpushMessage($service_order['member_id'], '您的服务服务已使用,请确认', $single_title, 4);



                            $ret = Db::name('order')->alias('o')->fetchSql(false)->where($where_id)->update(

                                ['shop_id' => $param['shop_id'],

                                    'is_read_shop' => 0,

                                    'multi_pic' => serialize(Request::instance()->param('picArr/a')),

                                    'explain' => $param['explain'],

                                ]);

                           Db::name('order o')->where($where_id)->where('status', 6)->update(['status' => 5]);

                            if($ret !== false){

                                //(new \app\index\controller\MemberMessage())->jpushMessage($service_order['member_id'], '您的服务订单已重新指派门店', '寄存门店:' . $shop_name , 2);

                                wingo('人员添加完毕', Url::build('index'));

                            }



                        }



                        //如果门店一致,并且没有添加人员

                        wingo('确认完毕', Url::build('index'));



                    }









                }else{ //门店分配人员

                    if(!empty($param['spec_id']) && !empty($param['number'])){ //服务商品

                        $service_order_goods = [];

                        for ($i=0;$i<count($param['spec_id']);$i++){

                            (new ServiceOrderGoods())->save([

                                'order_id' => $service_order['id'],

                                'cat_id' => $param['cat_id'][$i],

                                'spec_id' => $param['spec_id'][$i],

                                'number' => $param['number'][$i],

                                'create_time' => date('Y-m-d H:i:s',time())

                            ]);

                            $inventory = Db::name('shop_spec_attr')->where('id',$param['spec_id'][$i])->setDec('inventory',$param['number'][$i]);

//                                    $service_order_goods['order_id'] = $service_order['id'];

//                                    $service_order_goods['cat_id'] = $service_order['cat_id'];

//                                    $service_order_goods['spec_id'] = $service_order['spec_id'];

//                                    $service_order_goods['number'] = $service_order['number'];

//                                    $service_order_goods['create_time'] = $service_order['create_time'];

                        }

                        //(new ServiceOrderGoods())->saveAll($service_order_goods);

                    }



                    if (!empty($param['assignor_id'])) {

//                                $single_id = explode('-',$param['single_id'][0])[0];//门店服务分类 第一个类就代表所有相同的服务类了

//                                $single_title = Db::name('single')->where('id',$single_id)->value('cat_name');//服务类型

//                                $assignor_price = explode('-',$param['single_id'][0])[1];//门店金额

                        // 一对多添加数组

                        // 一对多添加数组

                        $shop_assignor_records = [];

                        for ($i = 0; $i < count($param['assignor_id']); $i++) {

                            $shop_assignor_records[$i]['order_id'] = $service_order['id'];

                            $shop_assignor_records[$i]['assignor_id'] = $param['assignor_id'][$i];

                            $shop_assignor_records[$i]['assignor_price'] = $param['assignor_price'][$i];

                            $shop_assignor_records[$i]['single_id'] = $param['single_id'][$i];

                            $shop_assignor_records[$i]['type'] = $param['typea'][$i];

                            $shop_assignor_records[$i]['assignor_content'] = $param['assignor_content'][$i];

                            $shop_assignor_records[$i]['create_time'] = date('Y-m-d H:i:s', time());

                            $shop_assignor_records[$i]['shop_id'] = \session('shop_id');

                            $shop_assignor_records[$i]['order_type'] = 2;

                            $shop_assignor_records[$i]['is_agree'] = 2;

//                                    Db::name('shop_assignor_records')->insert(

//                                        ['assignor_id' => $param['assignor_id'][$i],

//                                         'assignor_price' => $param['assignor_price'][$i],

//                                         'order_id' => $service_order['id'],

//                                         'order_type' => $service_order['order_type'],

//                                         'order_type' => $service_order['order_type'],

//                                         'create_time' => date('Y-m-d H:i:s',time()),

//                                         'shop_id' => \session('shop_id')

//                                        ]);

                        }

                        Db::name('shop_assignor_records')->insertAll($shop_assignor_records);

                        $last_id = Db::getLastInsID();

                        $single_title = Db::name('single')->where('id', $param['single_id'][0])->value('cat_name');

                        Db::name('member_message')->insert(

                            ['member_id' => $service_order['member_id'],

                                'order_number' => $last_id,

                                'type_id' => 4,

                                'title' => '您的服务服务已使用,请确认',

                                'content' => $service_order['order_number'],

                                'is_click' => 1,

                                'create_time' => date('Y-m-d H:i:s', time())

                            ]);



                        (new \app\index\controller\MemberMessage())->jpushMessage($service_order['member_id'], '您的服务服务已使用,请确认', $single_title, 4);

                        if($service_order['single_id'] == 11){

                            $t = explode('/',Request::instance()->param()['interval_timer']);

                            Db::name('order o')

                                ->where($where_id)

                                ->where($where_code)

                                ->where('status', 6)

                                ->update(['start_time' => $t[0],'end_time' => $t[1],'multi_pic' => serialize(Request::instance()->param('picArr/a'))]);

                        }

                        //门店确认不需要推送消息 所以注释了

                        $ret = Db::name('order o')->where($where_id)->where($where_code)->where('status', 6)->update(['status' => 5]);

                        //(new \app\index\controller\MemberMessage())->jpushMessage($service_order['member_id'], '您的服务订单已重新指派门店,请到店扫码验证', '寄存门店:' . $shop_name , 2);

                        if($service_order['single_id'] == 11){

                            wingo('人员分配完毕(轮胎寄存)', Url::build('index', ['code' => 1]));

                        }else{

                            wingo('人员分配完毕', Url::build('index', ['code' => 1]));

                        }



                    }else{

                        fail('请分配人员');

                    }



                }



            }

            if(in_array($service_order['status'],[5,4]) && $auding_status == 2){ //总台操作

                if(count(Request::instance()->param('picArr/a')) > 2){

                    fail('图片最多上传2张');

                }

                if (!empty($param['assignor_id']) && count($param['assignor_id']) != count(array_unique($param['assignor_id']))) {

                    //fail('服务人员不能重复');

                }

                if(isset($param['single_id']) && count(array_unique($param['single_id'])) >= 2){

                    //fail('一次只能服务一个分类');

                }



                if(empty(Request::instance()->param()['interval_timer'])){

                    $t[0] = $t[1] = '';

                }else{

                    $t = explode('/',Request::instance()->param()['interval_timer']);

                }

                Db::name('order o')

                    ->where($where_id)

                    ->where($where_code)

                    ->update(['explain' =>Request::instance()->param('explain',''),'start_time' => $t[0],'end_time' => $t[1],'multi_pic' => serialize(Request::instance()->param('picArr/a')),'yuyue_start_time' => $param['yuyue_start_time'],

                        'yuyue_end_time' => $param['yuyue_end_time']]);

                //Db::name('shop_assignor_records')->where('order_id',$service_order['id'])->delete();总后台先删除在添加不对

                //服务类门店服务人员只能添加一次 6到5



                if(!empty($param['spec_id']) && !empty($param['number'])){ //服务商品

                    $service_order_goods = [];

                    for ($i=0;$i<count($param['spec_id']);$i++){

                        (new ServiceOrderGoods())->save([

                            'order_id' => $service_order['id'],

                            'cat_id' => $param['cat_id'][$i],

                            'spec_id' => $param['spec_id'][$i],

                            'number' => $param['number'][$i],

                            'create_time' => date('Y-m-d H:i:s',time())

                        ]);

                        $inventory = Db::name('shop_spec_attr')->where('id',$param['spec_id'][$i])->setDec('inventory',$param['number'][$i]);

//                                    $service_order_goods['order_id'] = $service_order['id'];

//                                    $service_order_goods['cat_id'] = $service_order['cat_id'];

//                                    $service_order_goods['spec_id'] = $service_order['spec_id'];

//                                    $service_order_goods['number'] = $service_order['number'];

//                                    $service_order_goods['create_time'] = $service_order['create_time'];

                    }

                    //(new ServiceOrderGoods())->saveAll($service_order_goods);

                }



                if(!empty($param['assignor_id'])){



//                        $assignor_content = explode('-',$param['assignor_content'][0])[0];//门店服务分类 第一个类就代表所有相同的服务类了

//                        $single_title = Db::name('single')->where('id',$param['single_id'][0])->value('cat_name');//服务类型

//                        $assignor_price = explode('-',$param['assignor_content'][0])[1];//门店金额

                    for ($i = 0; $i < count($param['assignor_id']); $i++) {

                        //先删除当前order_id的记录 也就是删除当前门店的几率 循环删除更加不对了



                        //Db::name('shop_assignor_records')->where('order_id',$service_order['id'])->delete();

                        $ret =Db::name('shop_assignor_records')->insert(

                            [   'assignor_id' => $param['assignor_id'][$i],

                                'single_id' => $param['single_id'][$i],

                                'type' => $param['typea'][$i],

                                'assignor_price' => $param['assignor_price'][$i],

                                'assignor_content' => $param['assignor_content'][$i],

                                'order_id' => $service_order['id'],

                                'order_type' => $service_order['order_type'],

                                'create_time' => date('Y-m-d H:i:s',time()),

                                'shop_id' => $service_order['shop_id'],

                                'is_agree' => 2,

                            ]);



                    }



                }



                wingo('门店人员分配管理', Url::build('index', ['code' => 1]));

            }









            if ($service_order['status'] == 6 && $auding_status == 1) { //门店管理

                //$service_order['code'] == 2 && 暂时先不码卷验证



            }

//                if ($service_order['status'] == 6 && $service_order['code'] == 2 && $auding_status == 1 && $service_order['single_id'] == 11) {

//

//                    $t = explode('/', Request::instance()->param('interval_timer'));

//                    $multi_pic = serialize(Request::instance()->param('picArr/a'));

//                    $remark = Request::instance()->param('remark');

//

//                    $ret = Db::name('order o')->where($where_id)->where($where_code)->where('status', 6)->update(

//                        [

//                            'status' => 5,

//                            'start_time' => $t[0],

//                            'end_time' => $t[1],

//                            'multi_pic' => $multi_pic,

//                            'remark' => $remark

//                        ]);

//                    if ($ret !== false) {

//                        if(empty($param['assignor_id'])){

//                            fail('请添加门店人员');

//                        }

//                        if (!empty($param['assignor_id'])) {

//                            // 一对多添加数组

//                            $shop_assignor_records = [];

//                            for ($i = 0; $i < count($param['assignor_id']); $i++) {

//                                $shop_assignor_records[$i]['order_id'] = $service_order['id'];

//                                $shop_assignor_records[$i]['assignor_id'] = $param['assignor_id'][$i];

//                                $shop_assignor_records[$i]['assignor_price'] = $param['assignor_price'][$i];

//                                $shop_assignor_records[$i]['create_time'] = date('Y-m-d H:i:s', time());

//                            }

//

//                            Db::name('shop_assignor_records')->insertAll($shop_assignor_records);

//

//                        }

//                        win('人员分配完毕(轮胎寄存)', Url::build('index', ['code' => 1]));

//                    }

//                }



            if (isset($param['status']) && ($param['status'] >= 10)) {



                $fail_explain = Request::instance()->param('fail_explain','');

                if(strpos('5,7,8,9,10',(string)$level) === false){

                    fail('当前管理员无退款审核权限');

                }

                $refund_order_audit = Db::name('refund_order_audit')->where([

                    'order_id' => $service_order['id'],

                    'manage_id' => \session('manage_id'),

                ])->find();//当前管理员自己提交的数据

                if(!empty($refund_order_audit)) fail('已经申请过审核');

                if($level == 5){ //门店点击提交 店长-副经理-经理-财务-总经理

                    if(empty($refund_order_audit)){

                        (new RefundOrderAudit())->save([

                            'order_id' => $service_order['id'],

                            'manage_id' => \session('manage_id'),

                            'status' => input('post.status'),

                            'is_read' => 1,

                            'level' => $level,

                            'shop_id' => \session('shop_id'),

                            'shop_title' => Db::name('shop')->where('id',\session('shop_id'))->value('shop_title'),

                            'fail_explain' => $fail_explain,

                            'create_time' => date('Y-m-d H:i:s',time())

                        ]);

                        Db::name('order')->where('id',$service_order['id'])->setField('is_read_5',1);

                        if($param['status'] == 12){

                            Db::name('order')->where('id',$service_order['id'])->setField('status',6);

                        }

                        wingo('门店申请退款审核',Url::build('index'));

                    }else{

                        fail('已经申请审核');

                    }

                }

                $refund_order_audit_5 = Db::name('refund_order_audit')->where(['order_id' => $service_order['id'],'status' => 11, 'level' =>5])->find();//门店是否提交审核数据

                $refund_order_audit_7 = Db::name('refund_order_audit')->where(['order_id' => $service_order['id'],'status' => 11, 'level' =>7])->find();//门店是否提交审核数据

                $refund_order_audit_8 = Db::name('refund_order_audit')->where(['order_id' => $service_order['id'],'status' => 11, 'level' =>8])->find();//门店是否提交审核数据

                $refund_order_audit_9 = Db::name('refund_order_audit')->where(['order_id' => $service_order['id'],'status' => 11, 'level' =>9])->find();//门店是否提交审核数据

                if($level == 7){ //副经理

                    if(empty($refund_order_audit_5)) fail('门店没有通过退款审核');

                    $ret = (new RefundOrderAudit())->save([

                        'order_id' => $service_order['id'],

                        'manage_id' => \session('manage_id'),

                        'status' => input('post.status'),

                        'is_read' => 1,

                        'level' => $level,

                        'shop_id' => 0,

                        'fail_explain' => $fail_explain,

                        'create_time' => date('Y-m-d H:i:s',time())

                    ]);

                    Db::name('order')->where('id',$service_order['id'])->setField('is_read_7',1);

                    if($param['status'] == 12){

                        Db::name('order')->where('id',$service_order['id'])->setField('status',6);

                    }

                    if($ret){

                        wingo('副经理申请退款审核',Url::build('index'));

                    }



                }

                if($level == 8){ //经理



                    if(empty($refund_order_audit_5)) fail('门店没有通过退款审核');

                    if(empty($refund_order_audit_7)) fail('副经理没有通过退款审核');

                    $ret = (new RefundOrderAudit())->save([

                        'order_id' => $service_order['id'],

                        'manage_id' => \session('manage_id'),

                        'status' => input('post.status'),

                        'is_read' => 1,

                        'level' => $level,

                        'shop_id' => 0,

                        'fail_explain' => $fail_explain,

                        'create_time' => date('Y-m-d H:i:s',time())

                    ]);

                    Db::name('order')->where('id',$service_order['id'])->setField('is_read_8',1);

                    if($param['status'] == 12){

                        Db::name('order')->where('id',$service_order['id'])->setField('status',6);

                    }

                    if($ret){

                        wingo('经理申请退款审核',Url::build('index'));

                    }

                }

                if($level == 9){ //财务



                    if(empty($refund_order_audit_5)) fail('门店没有通过退款审核');

                    if(empty($refund_order_audit_7)) fail('副经理没有通过退款审核');

                    if(empty($refund_order_audit_8)) fail('经理没有通过退款审核');

                    Db::name('order')->where('id',$service_order['id'])->setField('is_read_9',1);

                    $ret = (new RefundOrderAudit())->save([

                        'order_id' => $service_order['id'],

                        'manage_id' => \session('manage_id'),

                        'status' => input('post.status'),

                        'is_read' => 1,

                        'level' => $level,

                        'shop_id' => 0,

                        'fail_explain' => $fail_explain,

                        'create_time' => date('Y-m-d H:i:s',time())

                    ]);

                    if($param['status'] == 12){

                        Db::name('order')->where('id',$service_order['id'])->setField('status',6);

                    }

                    if($ret){

                        wingo('财务申请退款审核',Url::build('index'));

                    }

                }

                if($level == 10){ //总经理



                    if(empty($refund_order_audit_5)) fail('门店没有通过退款审核');

                    if(empty($refund_order_audit_7)) fail('副经理没有通过退款审核');

                    if(empty($refund_order_audit_8)) fail('经理没有通过退款审核');

                    if(empty($refund_order_audit_9)) fail('财务没有通过退款审核');

                    Db::name('order')->where('id',$service_order['id'])->setField('is_read_10',1);

                    if($param['status'] == 12){

                        Db::name('order')->where('id',$service_order['id'])->setField('status',6);

                        Db::name('order')->where('id',$service_order['id'])->setField('refund_status',2);//下次不能再退款

                    }

                    if($param['status'] == 11){

                        $find = Db::name('order')->find($id);

                        if ($find['pay_type'] == '2') {

                            $ret = (new Alipay())->refund($find['order_number'], $refund['amount'], '', $find['shop_order_number']);

                            if ($ret->code !== '10000') {

                                fail($ret->sub_msg);

                            }

                            //halt($data['order_number'] . '-' . $data['price'] . '-' . $data['explain']);

                        } else if ($find['pay_type'] == '1') {

                            //halt('wx');

                            $ret = (new Alipay())->wechat($find['order_number'], $find['amount'], $refund['amount']);

                            if ($ret['result_code'] == 'FAIL') fail($ret['err_code_des']);

                        }

                        $ret = Db::name('order')->where('id', $param['id'])->update(['status' => $param['status']]);

                        if ($ret !== false) {

                            (new Order())->refund($find['member_id'], $find['order_number']);

                            $refund_ret = Db::name('order_refund')->where('order_id', $id)->update(['fail_explain' => $param['fail_explain']]);

                            if ($refund_ret !== false) {

                                win('退货款处理完毕', Url::build('index'));

                            }

                        }

                        $ret = (new RefundOrderAudit())->save([

                            'order_id' => $service_order['id'],

                            'manage_id' => \session('manage_id'),

                            'status' => input('post.status'),

                            'is_read' => 1,

                            'level' => $level,

                            'shop_id' => 0,

                            'fail_explain' => $fail_explain,

                            'create_time' => date('Y-m-d H:i:s',time())

                        ]);

                        if($ret){





                            Db::name('member_distribution_records')->where(['order_number' => $find['order_number']])->delete();

                            wingo('总经理同意退款中',Url::build('index'));

                        }

                    }



                }

















            }



//                if (isset($param['status']) && ($param['status'] == 12)) {

//                    //由10变成6

//                    $ret = Db::name('order')->where('id', $param['id'])->update(['status' => 6]);

//                    if ($ret !== false) {

//                        $refund_ret = Db::name('order_refund')->where('order_id', $id)->update(['fail_explain' => $param['fail_explain']]);

//                        if ($refund_ret !== false) {

//                            win('退货款失败处理完毕', Url::build('index'));

//                        }

//                    }

//                }

        } //提交数据





        $order = \app\console\model\Order::alias('o')

            ->join('member m', 'o.member_id = m.id','left')

            ->join('single se', 'o.single_parent_id = se.id', 'left')

            ->join('shop s', 'o.shop_id = s.id', 'left')

            ->field('o.*,m.username,m.is_certification,o.car_number o_car_number,m.brand_number,m.id_code,s.shop_title,se.cat_name')

            ->where($where_id)

            ->where($where_code)

            ->find();



//        dump($order);

        if ($order != null) {

            $order = $order->toArray();

            $order['one_cat'] = Db::name('single')->where('id', $order['single_id'])->value('cat_name');

        } else {

            fail('没有扫码订单');

        }

        if($order['is_certification'] != 2){

            //$order['car_number'] = $order['brand_number'] = $order['id_code'] = '';

        }

        if($order['single_parent_id'] == 1 || $order['single_parent_id'] == 2){

            $order['car_number'] = Db::name('order_service')->where('order_id',$order['id'])->value('plat_number');

            $order['brand_number'] = Db::name('order_service')->where('order_id',$order['id'])->value('brand_number');

            $order['id_code'] = Db::name('order_service')->where('order_id',$order['id'])->value('plat_code');

        }

        if ($order['status'] == 10 || $order['status'] == 11 || $order['status'] == 12) {

            $order['refund_create_time'] = Db::name('order_refund')->where('order_id', $order['id'])->value('create_time');

        }

        if ($order['service_type_id'] == 1 || $order['service_type_id'] == 2 || $order['service_type_id'] == 3) { //1保险 2年检

            $order['service_info'] = Db::name('order_service')

                ->where('order_id', $order['id'])

                ->find();

            foreach (explode(',', $order['service_info']['type_id_str']) as $k => $v) {

                $order['service_info']['type_id_name'][] = Db::name('protect_type')->where('id', $v)->value('title');

            }

        }



        //$shop_id = Db::name('shop_create')->where('manage_id',Session::get('manage_id'))->value('shop_id');//当前创建的门店id;

//        if(!empty(\session('shop_id'))){

//             $shop_id =  \session('shop_id');

//        }else{

//            $shop_id =

//        }

        $shop_id = $order['shop_id'];

        $shop_assignor = Db::name('shop_assignor')->where('is_delete',1)->select();//门店人员

        $shop_assignor_records = Db::name('shop_assignor_records sar')

            ->join('shop_assignor sa', 'sar.assignor_id = sa.id','left')

            ->join('single s','sar.single_id = s.id','left')

            ->where('order_id', $service_order['id'])

            ->field('sar.*,sa.name,s.cat_name')

            ->select();

        $is_agreee = '1,2';

        if(isset($param['table'])) $is_agreee = 2;

        if(\session('role_id') == 1){

            $is_show = [];

        }else{

            $is_show['sar.is_show'] = ['eq',1];

        }

        $shop_assignor_records = Db::name('shop_assignor_records sar')

            ->join('shop','shop.id = sar.shop_id','left')

            ->join('shop_assignor sa','sar.assignor_id = sa.id','left')

            ->join('single s','sar.single_id = s.id','left')

            ->join('goods_type gt','gt.id = sar.single_id','left')

            ->where('order_id', $service_order['id'])

            ->where($is_show)

            ->where('sar.is_agree','in',$is_agreee)

            ->field('sar.*,shop.shop_title,sa.name,s.cat_name,gt.title')

            ->select()->toArray();



        if(!empty($shop_assignor_records)){

            foreach ($shop_assignor_records as $k => &$v){

                if($v['type'] == 1){

                    $v['type'] = '服务提成';

                }

                if($v['type'] == 2){

                    $v['type'] = '销售提成';

                }

                if($v['order_type'] == 2){

                    $v['single_name'] = $v['cat_name'];

                }

                if($v['order_type'] == 1){

                    $v['single_name'] = $v['title'];

                }

                $v['assignor_content'] = Db::name('single')->where('id',$v['assignor_content'])->value('cat_name');

            }

        }

        //退款审核记录

        $refund_order_audit_records = (new RefundOrderAudit())

            ->alias('roa')

            ->join('manager m','roa.manage_id = m.id')

            ->field('roa.*,m.username')

            ->where('order_id',$order['id'])

            ->select();

        //审核会员数量 不管通过不通过;

        $count = (new RefundOrderAudit())->where('order_id',$order['id'])->where('status','11')->count();

        $refund_button = false; //这么判断 其他人员肯定是false

        if($level == 5){

            if($count == 0){

                $refund_button = true;

            }

        }

        if($level == 7){

            if($count == 1){

                $refund_button = true;

            }

        }

        if($level == 8){

            if($count == 2){

                $refund_button = true;

            }

        }

        if($level == 9){

            if($count == 3){

                $refund_button = true;

            }

        }

        if($level == 10){

            if($count == 4){

                $refund_button = true;

            }

        }

        if(\session('auding_status') == 2){

            $where = [];

        }else{

            $where['shop_id'] = ['eq',\session('shop_id')];

        }



        $spec_attr_list = (new \app\console\model\ShopGoods())

            ->alias('sg')

            ->where($where)

            ->join('shop_spec_attr ssa','sg.id = ssa.goods_id')

            ->join('shop s','ssa.shop_id = s.id')

            ->where('ssa.shop_id','eq',$shop_id)

            ->field('sg.title,ssa.*,s.shop_title')

            ->where('s.auding_status',2)

            ->where('s.is_delete',1)

            ->paginate(1000)->each(function ($item, $key){



            });



        $service_order_goods = Db::name('service_order_goods')->where('order_id',$service_order['id'])->select();

        $service_people_price = Db::name('shop_service_price')

            ->alias('ssp')

            ->join('single s','ssp.single_id = s.id','right')

            ->where('shop_id',$shop_id)

            ->where('s.id',$order['single_parent_id'])

            ->where('s.parent_id','eq',0)

            ->where('auding_status',2)

            ->where('is_delete',1)

            ->field('s.id,s.cat_name,ssp.person_price')

            ->select(); //服务人员提成;

        if(session('role_id') != 1){

            $order['username'] = hideStr($order['username'],1,6);

        }



        $service_people_price2 = Db::name('shop_service_price')

            ->alias('ssp')

            ->join('single s','ssp.single_id = s.id','left')

            ->where('shop_id',$shop_id)

            ->where('s.id',$order['single_id'])



            ->field('s.id,s.cat_name,ssp.person_price')

            ->select(); //服务人员提成;



        $mwhere['status'] = ['eq',1];

        $mwhere['start_time'] = ['elt',time()];

        $mwhere['end_time'] = ['gt',time()];

        $mwhere = "(type = 2 and single_id = '{$order['single_id']}') or type = 3 and status = 1";



        $result = (new  \app\index\model\MemberCoupon)->where($mwhere)

            ->field('id,type,single_id,title,minus_price,total_price,content,status,start_time,end_time')

            ->where('total_price','elt',$order['order_price'])

            ->order(['id' => 'desc'])

            ->fetchSql(false)

            //->whereOr('type',3)

            ->where('member_id',$order['member_id'])

            ->select();

        //echo Db::getlastsql();

        //dump($result->toArray());

       // dump($result->toArray());

        if($service_people_price2->isEmpty()){

            //fail('人员提成或者分类错误');

        }

        $service_people_price2_first = '';

        if(!$service_people_price2->isEmpty()) $service_people_price2_first = $service_people_price2->toArray()[0]['person_price'];

        $template = '';

        if(isset($param['table'])) $template = 'service_order_table';



        $member_car_list1 = Db::name('member')->where('id',$order['member_id'])->column('car_number');

        $member_car_list2 = Db::name('member_car_list')->where('member_id',$order['member_id'])->group('car_number')->column('car_number');

        $member_car_list3 = Db::name('order')->where('member_id',$order['member_id'])->group('car_number')->column('car_number');

        $member_car_list4 = array_merge($member_car_list1,$member_car_list2,$member_car_list3);

        $member_car_list4 = array_unique($member_car_list4);

        if(!empty($member_car_list4)){

            foreach ($member_car_list4 as $k =>&$v){

                if(empty($v)){

                    unset($member_car_list4[$k]);

                }

            }

        }





        $user_coupon = http_gets("http://lihai.xmdonkey.com/index.php/index/member_coupon/index/member_id/{$order['member_id']}/status/1/order_price/{$order['order_price']}/type/2/single_id/{$order['single_id']}");

        $coupon_array = json_decode($user_coupon,true)['data']['data'];

//        halt($order);

        return view($template, ['item' => $order,

            'member_car_list4' => $member_car_list4,

            'member_coupon' => $coupon_array,

            'service_people_price2' => json_encode($service_people_price2->toArray()),

            'service_people_price2_first' => $service_people_price2_first,

            'refund' => $refund,

            'service_people_price' => $service_people_price,

            'shop_assignor' => $shop_assignor,

            'shop_assignor_records' => $shop_assignor_records,

            'refund_order_audit_records' => $refund_order_audit_records,

            'refund_button' => $refund_button,

            'spec_attr_list' => json_encode($spec_attr_list->toArray()['data']),

            'category' => json_encode(ClassifyAlias::dimension(Cache::get('goodsType'))),

            'service_order_goods' => $service_order_goods

        ]);

    }



    public function update_dayin()

    {



        $auding_status = Session::get('auding_status');

        $level = \session('role_id');//当前登录的管理员界别 5 7 8 9 10

        $number = db('config')->where('varname', 'web_number')->value('varvalue');

        $id = Request::instance()->param('id', '');

        $where_id = [];

        if ($id) {

            $where_id['o.id'] = ['eq', $id];

            if ($auding_status == 2) {

                Db::name('order o')->where($where_id)->setField('is_read', 1);

            } else {

                Db::name('order o')->where($where_id)->setField('is_read_shop', 1);

            }

        }

        $where_code = [];



        $param = Request::instance()->param();



        if (isset($param['code'])) {

            $date = date('Y-m-d H:i:s', time() - 300);

            $where_code['o.code'] = ['eq', 2];

            $where_code['o.status'] = ['eq', 6];

            $where_code['o.code_time'] = ['egt', $date];

        }

        $service_order = Db::name('order o')->where($where_id)->where($where_code)->find();

        $refund = Db::name('order_refund ors')->field('ors.*,rr.title')->where('order_id', $service_order['id'])->join('refund_reason rr', 'ors.reason_id = rr.id')->find();

        if (Request::instance()->isPost()) {



            $shop_name = Db::name('shop')->where('id', $service_order['shop_id'])->value('shop_title');

            if ($service_order['single_id'] != 11) { //非轮胎寄存包含汽车保险类

                if($service_order['status'] == 50){

                    if ($param['amount'] <= 0) {

                        fail('请填写正确派单金额');

                    }

                    if ($param['shop_id'] <= 0) {

                        fail('请填写派单门店');

                    }

                    if ($param['freight'] > 0) { //商家配送

                        $ret = Db::name('order')->alias('o')

                            ->fetchSql(false)

                            ->where($where_id)

                            ->update([

                                'shop_id' => $param['shop_id'],

                                'amount' => $param['amount'] + $param['freight']+$param['sj'],

                                'order_price' => $param['amount'],

                                'freight' => $param['freight'],

                                'sj' => $param['sj'],

                                'status' => 1, 'shipping' => 1,

                                'is_read_shop' =>0,

                                'explain' => $param['explain'],

                                'shipping_province' => $param['shipping_province'],

                                'shipping_address' => $param['shipping_address'],

                                'shipping_phone' => $param['shipping_phone'],

                                'shipping_name' => $param['shipping_name'],

                            ]);



                    } else { //门店自提

                        $ret = Db::name('order')->alias('o')->fetchSql(false)->where($where_id)->update(

                            [   'shop_id' => $param['shop_id'],

                                'amount' => $param['amount']+$param['sj'],

                                'order_price' => $param['amount'],

                                'sj' => $param['sj'],

                                'status' => 1, 'shipping' => 2,

                                'is_read_shop' =>0,

                                'explain' => $param['explain'],

                                'shipping_province' => '',

                                'shipping_address' => '',

                                'shipping_phone' => '',

                                'shipping_name' => ''

                            ]);

                    }

                    if ($ret) {

                        Db::name('member_message')->insert(

                            ['member_id' => $service_order['member_id'],

                                'order_number' => $service_order['order_number'],

                                'type_id' => 2,

                                'title' => '您的订单金额及门店已确认,请支付',

                                'content' => $service_order['order_number'],

                                'is_click' => 1,

                                'create_time' => date('Y-m-d H:i:s', time())

                            ]);



                        (new \app\index\controller\MemberMessage())->jpushMessage($service_order['member_id'], '您的订单金额及门店已确认,请支付', '订单金额:' . ($param['amount'] + $param['freight']) . '元,运费:' . $param['freight'] . '元', 2);

                        win('订单金额及门店指派完毕', Url::build('index'));

                    }

                }

                //非轮胎寄存

            }else{

                //轮胎寄存



                if($service_order['status'] == 50){

                    $t = explode('/',Request::instance()->param()['interval_timer']);

                    if(empty(Request::instance()->param()['interval_timer'])){

                        $t[0] = $t[1] = '';

                    }

                    if ($param['shop_id'] <= 0) {

                        fail('请指派有效门店');

                    }



                    if ($param['amount'] > 0) {



                        $ret = Db::name('order o')->where('id', $id)->update(['shop_id' => $param['shop_id'], 'amount' => $param['amount'], 'order_price' => $param['amount'], 'status' => 1,'is_read_shop' =>0,'start_time' => $t[0],'end_time' => $t[1],'multi_pic' => serialize(Request::instance()->param('picArr/a')),]);

                        if ($ret !== false) {

                            $hah = Db::name('member_message')->where('order_number', $service_order['order_number'])->update(

                                [

                                    'title' => '您的服务订单(轮胎寄存)已指派门店,请立即支付',

                                    'content' => $service_order['order_number'],

                                    'is_click' => 1,

                                    'create_time' => date('Y-m-d H:i:s', time())

                                ]);



                            $shop_name = Db::name('shop')->where('id', $service_order['shop_id'])->value('shop_title');

                            (new \app\index\controller\MemberMessage())->jpushMessage($service_order['member_id'], '您的服务订单(轮胎寄存)已指派门店,请立即支付', '寄存门店:' . $shop_name . ' 寄存金额为:' . $param['amount'] . '元', 2);

                            win('门店指派完毕(付费)', Url::build('index'));

                        }

                    } else {

                        $ret = Db::name('order o')->where('id', $id)->update(['shop_id' => $param['shop_id'],'amount' => 0, 'order_price' => 0, 'status' => 6,'is_read_shop' =>0,'start_time' => $t[0],'end_time' => $t[1],'multi_pic' => serialize(Request::instance()->param('picArr/a')),]);//免费寄存

                        if ($ret !== false) {

                            $hah = Db::name('member_message')->where('order_number', $service_order['order_number'])->update(

                                [

                                    'title' => '您的服务订单(轮胎寄存)已指派门店,请立即支付',

                                    'content' => $service_order['order_number'],

                                    'is_click' => 1,

                                    'create_time' => date('Y-m-d H:i:s', time())

                                ]);





                            (new \app\index\controller\MemberMessage())->jpushMessage($service_order['member_id'], '您的服务订单(轮胎寄存)已指派门店,请立即支付', '寄存门店:' . $shop_name . ' 免费寄存', 2);

                            win('门店指派完毕(免费)', Url::build('index'));

                        }

                    }



                    //第一次下单50状态

                }

                if($service_order['status'] == 5 || $service_order['status'] == 4){



                    //20190828新添加进行中状态

                    if (!empty($param['assignor_id'])) {

//                                $single_id = explode('-',$param['single_id'][0])[0];//门店服务分类 第一个类就代表所有相同的服务类了

//                                $single_title = Db::name('single')->where('id',$single_id)->value('cat_name');//服务类型

//                                $assignor_price = explode('-',$param['single_id'][0])[1];//门店金额

                        // 一对多添加数组

                        // 一对多添加数组

                        $shop_assignor_records = [];

                        for ($i = 0; $i < count($param['assignor_id']); $i++) {

                            $shop_assignor_records[$i]['order_id'] = $service_order['id'];

                            $shop_assignor_records[$i]['assignor_id'] = $param['assignor_id'][$i];

                            $shop_assignor_records[$i]['assignor_price'] = $param['assignor_price'][$i];

                            $shop_assignor_records[$i]['single_id'] = $param['single_id'][$i];

                            $shop_assignor_records[$i]['assignor_content'] = $param['assignor_content'][$i];

                            $shop_assignor_records[$i]['create_time'] = date('Y-m-d H:i:s', time());

                            $shop_assignor_records[$i]['shop_id'] = \session('shop_id');

                            $shop_assignor_records[$i]['order_type'] = 2;

                            $shop_assignor_records[$i]['is_agree'] = 2;

//                                    Db::name('shop_assignor_records')->insert(

//                                        ['assignor_id' => $param['assignor_id'][$i],

//                                         'assignor_price' => $param['assignor_price'][$i],

//                                         'order_id' => $service_order['id'],

//                                         'order_type' => $service_order['order_type'],

//                                         'order_type' => $service_order['order_type'],

//                                         'create_time' => date('Y-m-d H:i:s',time()),

//                                         'shop_id' => \session('shop_id')

//                                        ]);

                        }

                        Db::name('shop_assignor_records')->insertAll($shop_assignor_records);

                        win('人员（轮胎）添加完毕', Url::build('index'));



                    }





                }







                //轮胎寄存

            }



            if(in_array($service_order['status'],[1,6])){ //待支付和进行中 重新指派门店

                //任何时候都可以设置预约时间



                $ret = Db::name('order')->alias('o')->fetchSql(false)->where($where_id)->update(

                    [

                        'yuyue_start_time' => $param['yuyue_start_time'],

                        'yuyue_end_time' => $param['yuyue_end_time']

                    ]);

                if(count(Request::instance()->param('picArr/a')) > 2){

                    fail('图片最多上传2张');

                }

                if (!empty($param['assignor_id']) && count($param['assignor_id']) != count(array_unique($param['assignor_id']))) {

                    //fail('服务人员不能重复');

                }

                if(isset($param['single_id']) && count(array_unique($param['single_id'])) >= 2){

                    //fail('一次只能服务一个分类');

                }

                if($auding_status == 2){ //总后台6状态

                    if ($param['amount'] <= 0) {

                        if($service_order['single_id'] != 11){

                            fail('请填写正确派单金额');

                        }



                    }

                    if ($param['shop_id'] <= 0) {

                        fail('请填写派单门店');

                    }



                    //当前数据和添加的不一致就是修改了

                    if($param['shop_id'] != $service_order['shop_id']){

                        //where('shop_id',$service_order['shop_id'])->

                        Db::name('shop_assignor_records')->where('order_id',$service_order['id'])->delete();

                        $ret = Db::name('order')->alias('o')->fetchSql(false)->where($where_id)->update(

                            ['shop_id' => $param['shop_id'],

                                'is_read_shop' => 0,

                                'multi_pic' => serialize(Request::instance()->param('picArr/a')),

                                'explain' => $param['explain'],

                                'yuyue_start_time' => $param['yuyue_start_time'],

                                'yuyue_end_time' => $param['yuyue_end_time']

                            ]);

                        win('重新指派门店完毕', Url::build('index'));



                    }else{

                        //20190828新添加进行中状态

                        if (!empty($param['assignor_id'])) {

//                                $single_id = explode('-',$param['single_id'][0])[0];//门店服务分类 第一个类就代表所有相同的服务类了

//                                $single_title = Db::name('single')->where('id',$single_id)->value('cat_name');//服务类型

//                                $assignor_price = explode('-',$param['single_id'][0])[1];//门店金额

                            // 一对多添加数组

                            // 一对多添加数组

                            $shop_assignor_records = [];

                            for ($i = 0; $i < count($param['assignor_id']); $i++) {

                                $shop_assignor_records[$i]['order_id'] = $service_order['id'];

                                $shop_assignor_records[$i]['assignor_id'] = $param['assignor_id'][$i];

                                $shop_assignor_records[$i]['assignor_price'] = $param['assignor_price'][$i];

                                $shop_assignor_records[$i]['single_id'] = $param['single_id'][$i];

                                $shop_assignor_records[$i]['assignor_content'] = $param['assignor_content'][$i];

                                $shop_assignor_records[$i]['create_time'] = date('Y-m-d H:i:s', time());

                                $shop_assignor_records[$i]['shop_id'] = \session('shop_id');

                                $shop_assignor_records[$i]['order_type'] = 2;

                                $shop_assignor_records[$i]['is_agree'] = 2;

//                                    Db::name('shop_assignor_records')->insert(

//                                        ['assignor_id' => $param['assignor_id'][$i],

//                                         'assignor_price' => $param['assignor_price'][$i],

//                                         'order_id' => $service_order['id'],

//                                         'order_type' => $service_order['order_type'],

//                                         'order_type' => $service_order['order_type'],

//                                         'create_time' => date('Y-m-d H:i:s',time()),

//                                         'shop_id' => \session('shop_id')

//                                        ]);

                            }

                            Db::name('shop_assignor_records')->insertAll($shop_assignor_records);

                            $ret = Db::name('order')->alias('o')->fetchSql(false)->where($where_id)->update(

                                ['shop_id' => $param['shop_id'],

                                    'is_read_shop' => 0,

                                    'multi_pic' => serialize(Request::instance()->param('picArr/a')),

                                    'explain' => $param['explain'],

                                ]);

                            if($ret !== false){

                                //(new \app\index\controller\MemberMessage())->jpushMessage($service_order['member_id'], '您的服务订单已重新指派门店', '寄存门店:' . $shop_name , 2);

                                win('人员添加完毕', Url::build('index'));

                            }



                        }



                        //如果门店一致,并且没有添加人员

                        win('确认完毕', Url::build('index'));



                    }









                }else{ //门店分配人员

                    if(!empty($param['spec_id']) && !empty($param['number'])){ //服务商品

                        $service_order_goods = [];

                        for ($i=0;$i<count($param['spec_id']);$i++){

                            (new ServiceOrderGoods())->save([

                                'order_id' => $service_order['id'],

                                'cat_id' => $param['cat_id'][$i],

                                'spec_id' => $param['spec_id'][$i],

                                'number' => $param['number'][$i],

                                'create_time' => date('Y-m-d H:i:s',time())

                            ]);

                            $inventory = Db::name('shop_spec_attr')->where('id',$param['spec_id'][$i])->setDec('inventory',$param['number'][$i]);

//                                    $service_order_goods['order_id'] = $service_order['id'];

//                                    $service_order_goods['cat_id'] = $service_order['cat_id'];

//                                    $service_order_goods['spec_id'] = $service_order['spec_id'];

//                                    $service_order_goods['number'] = $service_order['number'];

//                                    $service_order_goods['create_time'] = $service_order['create_time'];

                        }

                        //(new ServiceOrderGoods())->saveAll($service_order_goods);

                    }



                    if (!empty($param['assignor_id'])) {

//                                $single_id = explode('-',$param['single_id'][0])[0];//门店服务分类 第一个类就代表所有相同的服务类了

//                                $single_title = Db::name('single')->where('id',$single_id)->value('cat_name');//服务类型

//                                $assignor_price = explode('-',$param['single_id'][0])[1];//门店金额

                        // 一对多添加数组

                        // 一对多添加数组

                        $shop_assignor_records = [];

                        for ($i = 0; $i < count($param['assignor_id']); $i++) {

                            $shop_assignor_records[$i]['order_id'] = $service_order['id'];

                            $shop_assignor_records[$i]['assignor_id'] = $param['assignor_id'][$i];

                            $shop_assignor_records[$i]['assignor_price'] = $param['assignor_price'][$i];

                            $shop_assignor_records[$i]['single_id'] = $param['single_id'][$i];

                            $shop_assignor_records[$i]['assignor_content'] = $param['assignor_content'][$i];

                            $shop_assignor_records[$i]['create_time'] = date('Y-m-d H:i:s', time());

                            $shop_assignor_records[$i]['shop_id'] = \session('shop_id');

                            $shop_assignor_records[$i]['order_type'] = 2;

                            $shop_assignor_records[$i]['is_agree'] = 2;

//                                    Db::name('shop_assignor_records')->insert(

//                                        ['assignor_id' => $param['assignor_id'][$i],

//                                         'assignor_price' => $param['assignor_price'][$i],

//                                         'order_id' => $service_order['id'],

//                                         'order_type' => $service_order['order_type'],

//                                         'order_type' => $service_order['order_type'],

//                                         'create_time' => date('Y-m-d H:i:s',time()),

//                                         'shop_id' => \session('shop_id')

//                                        ]);

                        }

                        Db::name('shop_assignor_records')->insertAll($shop_assignor_records);

                        if($service_order['single_id'] == 11){

                            $t = explode('/',Request::instance()->param()['interval_timer']);

                            Db::name('order o')

                                ->where($where_id)

                                ->where($where_code)

                                ->where('status', 6)

                                ->update(['start_time' => $t[0],'end_time' => $t[1],'multi_pic' => serialize(Request::instance()->param('picArr/a'))]);

                        }

                        //门店确认不需要推送消息 所以注释了

                        $ret = Db::name('order o')->where($where_id)->where($where_code)->where('status', 6)->update(['status' => 5]);

                        //(new \app\index\controller\MemberMessage())->jpushMessage($service_order['member_id'], '您的服务订单已重新指派门店,请到店扫码验证', '寄存门店:' . $shop_name , 2);

                        if($service_order['single_id'] == 11){

                            win('人员分配完毕(轮胎寄存)', Url::build('index', ['code' => 1]));

                        }else{

                            win('人员分配完毕', Url::build('index', ['code' => 1]));

                        }



                    }else{

                        fail('请分配人员');

                    }



                }



            }

            if(in_array($service_order['status'],[5,4]) && $auding_status == 2){ //总台操作

                if(count(Request::instance()->param('picArr/a')) > 2){

                    fail('图片最多上传2张');

                }

                if (!empty($param['assignor_id']) && count($param['assignor_id']) != count(array_unique($param['assignor_id']))) {

                    //fail('服务人员不能重复');

                }

                if(isset($param['single_id']) && count(array_unique($param['single_id'])) >= 2){

                    //fail('一次只能服务一个分类');

                }



                if(empty(Request::instance()->param()['interval_timer'])){

                    $t[0] = $t[1] = '';

                }else{

                    $t = explode('/',Request::instance()->param()['interval_timer']);

                }

                Db::name('order o')

                    ->where($where_id)

                    ->where($where_code)

                    ->update(['explain' =>Request::instance()->param('explain',''),'start_time' => $t[0],'end_time' => $t[1],'multi_pic' => serialize(Request::instance()->param('picArr/a')),'yuyue_start_time' => $param['yuyue_start_time'],

                        'yuyue_end_time' => $param['yuyue_end_time']]);

                //Db::name('shop_assignor_records')->where('order_id',$service_order['id'])->delete();总后台先删除在添加不对

                //服务类门店服务人员只能添加一次 6到5



                if(!empty($param['spec_id']) && !empty($param['number'])){ //服务商品

                    $service_order_goods = [];

                    for ($i=0;$i<count($param['spec_id']);$i++){

                        (new ServiceOrderGoods())->save([

                            'order_id' => $service_order['id'],

                            'cat_id' => $param['cat_id'][$i],

                            'spec_id' => $param['spec_id'][$i],

                            'number' => $param['number'][$i],

                            'create_time' => date('Y-m-d H:i:s',time())

                        ]);

                        $inventory = Db::name('shop_spec_attr')->where('id',$param['spec_id'][$i])->setDec('inventory',$param['number'][$i]);

//                                    $service_order_goods['order_id'] = $service_order['id'];

//                                    $service_order_goods['cat_id'] = $service_order['cat_id'];

//                                    $service_order_goods['spec_id'] = $service_order['spec_id'];

//                                    $service_order_goods['number'] = $service_order['number'];

//                                    $service_order_goods['create_time'] = $service_order['create_time'];

                    }

                    //(new ServiceOrderGoods())->saveAll($service_order_goods);

                }



                if(!empty($param['assignor_id'])){



//                        $assignor_content = explode('-',$param['assignor_content'][0])[0];//门店服务分类 第一个类就代表所有相同的服务类了

//                        $single_title = Db::name('single')->where('id',$param['single_id'][0])->value('cat_name');//服务类型

//                        $assignor_price = explode('-',$param['assignor_content'][0])[1];//门店金额

                    for ($i = 0; $i < count($param['assignor_id']); $i++) {

                        //先删除当前order_id的记录 也就是删除当前门店的几率 循环删除更加不对了



                        //Db::name('shop_assignor_records')->where('order_id',$service_order['id'])->delete();

                        $ret =Db::name('shop_assignor_records')->insert(

                            [   'assignor_id' => $param['assignor_id'][$i],

                                'single_id' => $param['single_id'][$i],

                                'assignor_price' => $param['assignor_price'][$i],

                                'assignor_content' => $param['assignor_content'][$i],

                                'order_id' => $service_order['id'],

                                'order_type' => $service_order['order_type'],

                                'create_time' => date('Y-m-d H:i:s',time()),

                                'shop_id' => $service_order['shop_id'],

                                'is_agree' => 2,

                            ]);



                    }

                }



                win('门店人员分配管理', Url::build('index', ['code' => 1]));

            }









            if ($service_order['status'] == 6 && $auding_status == 1) { //门店管理

                //$service_order['code'] == 2 && 暂时先不码卷验证



            }

//                if ($service_order['status'] == 6 && $service_order['code'] == 2 && $auding_status == 1 && $service_order['single_id'] == 11) {

//

//                    $t = explode('/', Request::instance()->param('interval_timer'));

//                    $multi_pic = serialize(Request::instance()->param('picArr/a'));

//                    $remark = Request::instance()->param('remark');

//

//                    $ret = Db::name('order o')->where($where_id)->where($where_code)->where('status', 6)->update(

//                        [

//                            'status' => 5,

//                            'start_time' => $t[0],

//                            'end_time' => $t[1],

//                            'multi_pic' => $multi_pic,

//                            'remark' => $remark

//                        ]);

//                    if ($ret !== false) {

//                        if(empty($param['assignor_id'])){

//                            fail('请添加门店人员');

//                        }

//                        if (!empty($param['assignor_id'])) {

//                            // 一对多添加数组

//                            $shop_assignor_records = [];

//                            for ($i = 0; $i < count($param['assignor_id']); $i++) {

//                                $shop_assignor_records[$i]['order_id'] = $service_order['id'];

//                                $shop_assignor_records[$i]['assignor_id'] = $param['assignor_id'][$i];

//                                $shop_assignor_records[$i]['assignor_price'] = $param['assignor_price'][$i];

//                                $shop_assignor_records[$i]['create_time'] = date('Y-m-d H:i:s', time());

//                            }

//

//                            Db::name('shop_assignor_records')->insertAll($shop_assignor_records);

//

//                        }

//                        win('人员分配完毕(轮胎寄存)', Url::build('index', ['code' => 1]));

//                    }

//                }



            if (isset($param['status']) && ($param['status'] >= 10)) {



                $fail_explain = Request::instance()->param('fail_explain','');

                if(strpos('5,7,8,9,10',(string)$level) === false){

                    fail('当前管理员无退款审核权限');

                }

                $refund_order_audit = Db::name('refund_order_audit')->where([

                    'order_id' => $service_order['id'],

                    'manage_id' => \session('manage_id'),

                ])->find();//当前管理员自己提交的数据

                if(!empty($refund_order_audit)) fail('已经申请过审核');

                if($level == 5){ //门店点击提交 店长-副经理-经理-财务-总经理

                    if(empty($refund_order_audit)){

                        (new RefundOrderAudit())->save([

                            'order_id' => $service_order['id'],

                            'manage_id' => \session('manage_id'),

                            'status' => $param['status'],

                            'is_read' => 1,

                            'level' => $level,

                            'shop_id' => \session('shop_id'),

                            'shop_title' => Db::name('shop')->where('id',\session('shop_id'))->value('shop_title'),

                            'fail_explain' => $fail_explain,

                            'create_time' => date('Y-m-d H:i:s',time())

                        ]);

                        Db::name('order')->where('id',$service_order['id'])->setField('is_read_5',1);

                        if($param['status'] == 12){

                            Db::name('order')->where('id',$service_order['id'])->setField('status',6);

                        }

                        win('门店申请退款审核',Url::build('index'));

                    }else{

                        fail('已经申请审核');

                    }

                }

                $refund_order_audit_5 = Db::name('refund_order_audit')->where(['order_id' => $service_order['id'],'status' => 11, 'level' =>5])->find();//门店是否提交审核数据

                $refund_order_audit_7 = Db::name('refund_order_audit')->where(['order_id' => $service_order['id'],'status' => 11, 'level' =>7])->find();//门店是否提交审核数据

                $refund_order_audit_8 = Db::name('refund_order_audit')->where(['order_id' => $service_order['id'],'status' => 11, 'level' =>8])->find();//门店是否提交审核数据

                $refund_order_audit_9 = Db::name('refund_order_audit')->where(['order_id' => $service_order['id'],'status' => 11, 'level' =>9])->find();//门店是否提交审核数据

                if($level == 7){ //副经理

                    if(empty($refund_order_audit_5)) fail('门店没有通过退款审核');

                    $ret = (new RefundOrderAudit())->save([

                        'order_id' => $service_order['id'],

                        'manage_id' => \session('manage_id'),

                        'status' => $param['status'],

                        'is_read' => 1,

                        'level' => $level,

                        'shop_id' => 0,

                        'fail_explain' => $fail_explain,

                        'create_time' => date('Y-m-d H:i:s',time())

                    ]);

                    Db::name('order')->where('id',$service_order['id'])->setField('is_read_7',1);

                    if($param['status'] == 12){

                        Db::name('order')->where('id',$service_order['id'])->setField('status',6);

                    }

                    if($ret){

                        win('副经理申请退款审核',Url::build('index'));

                    }



                }

                if($level == 8){ //经理



                    if(empty($refund_order_audit_5)) fail('门店没有通过退款审核');

                    if(empty($refund_order_audit_7)) fail('副经理没有通过退款审核');

                    $ret = (new RefundOrderAudit())->save([

                        'order_id' => $service_order['id'],

                        'manage_id' => \session('manage_id'),

                        'status' => $param['status'],

                        'is_read' => 1,

                        'level' => $level,

                        'shop_id' => 0,

                        'fail_explain' => $fail_explain,

                        'create_time' => date('Y-m-d H:i:s',time())

                    ]);

                    Db::name('order')->where('id',$service_order['id'])->setField('is_read_8',1);

                    if($param['status'] == 12){

                        Db::name('order')->where('id',$service_order['id'])->setField('status',6);

                    }

                    if($ret){

                        win('经理申请退款审核',Url::build('index'));

                    }

                }

                if($level == 9){ //财务



                    if(empty($refund_order_audit_5)) fail('门店没有通过退款审核');

                    if(empty($refund_order_audit_7)) fail('副经理没有通过退款审核');

                    if(empty($refund_order_audit_8)) fail('经理没有通过退款审核');

                    Db::name('order')->where('id',$service_order['id'])->setField('is_read_9',1);

                    $ret = (new RefundOrderAudit())->save([

                        'order_id' => $service_order['id'],

                        'manage_id' => \session('manage_id'),

                        'status' => $param['status'],

                        'is_read' => 1,

                        'level' => $level,

                        'shop_id' => 0,

                        'fail_explain' => $fail_explain,

                        'create_time' => date('Y-m-d H:i:s',time())

                    ]);

                    if($param['status'] == 12){

                        Db::name('order')->where('id',$service_order['id'])->setField('status',6);

                    }

                    if($ret){

                        win('财务申请退款审核',Url::build('index'));

                    }

                }

                if($level == 10){ //总经理



                    if(empty($refund_order_audit_5)) fail('门店没有通过退款审核');

                    if(empty($refund_order_audit_7)) fail('副经理没有通过退款审核');

                    if(empty($refund_order_audit_8)) fail('经理没有通过退款审核');

                    if(empty($refund_order_audit_9)) fail('财务没有通过退款审核');

                    Db::name('order')->where('id',$service_order['id'])->setField('is_read_10',1);

                    if($param['status'] == 12){

                        Db::name('order')->where('id',$service_order['id'])->setField('status',6);

                        Db::name('order')->where('id',$service_order['id'])->setField('refund_status',2);//下次不能再退款

                    }

                    if($param['status'] == 11){

                        $find = Db::name('order')->find($id);

                        if ($find['pay_type'] == '2') {

                            $ret = (new Alipay())->refund($find['order_number'], $refund['amount'], '', $find['shop_order_number']);

                            if ($ret->code !== '10000') {

                                fail($ret->sub_msg);

                            }

                            //halt($data['order_number'] . '-' . $data['price'] . '-' . $data['explain']);

                        } else if ($find['pay_type'] == '1') {

                            //halt('wx');

                            $ret = (new Alipay())->wechat($find['order_number'], $find['amount'], $refund['amount']);

                            if ($ret['result_code'] == 'FAIL') fail($ret['err_code_des']);

                        }

                        $ret = Db::name('order')->where('id', $param['id'])->update(['status' => $param['status']]);

                        if ($ret !== false) {

                            (new Order())->refund($find['member_id'], $find['order_number']);

                            $refund_ret = Db::name('order_refund')->where('order_id', $id)->update(['fail_explain' => $param['fail_explain']]);

                            if ($refund_ret !== false) {

                                win('退货款处理完毕', Url::build('index'));

                            }

                        }

                        $ret = (new RefundOrderAudit())->save([

                            'order_id' => $service_order['id'],

                            'manage_id' => \session('manage_id'),

                            'status' => $param['status'],

                            'is_read' => 1,

                            'level' => $level,

                            'shop_id' => 0,

                            'fail_explain' => $fail_explain,

                            'create_time' => date('Y-m-d H:i:s',time())

                        ]);

                        if($ret){

                            win('总经理同意退款中',Url::build('index'));

                        }

                    }



                }

















            }



//                if (isset($param['status']) && ($param['status'] == 12)) {

//                    //由10变成6

//                    $ret = Db::name('order')->where('id', $param['id'])->update(['status' => 6]);

//                    if ($ret !== false) {

//                        $refund_ret = Db::name('order_refund')->where('order_id', $id)->update(['fail_explain' => $param['fail_explain']]);

//                        if ($refund_ret !== false) {

//                            win('退货款失败处理完毕', Url::build('index'));

//                        }

//                    }

//                }

        } //提交数据





        $order = \app\console\model\Order::alias('o')

            ->join('member m', 'o.member_id = m.id','left')

            ->join('single se', 'o.single_parent_id = se.id', 'left')

            ->join('shop s', 'o.shop_id = s.id', 'left')

            ->field('o.*,m.username,m.is_certification,m.car_number,m.brand_number,m.id_code,s.shop_title,se.cat_name')

            ->where($where_id)

            ->where($where_code)

            ->find();

        if ($order != null) {

            $order = $order->toArray();

            $order['one_cat'] = Db::name('single')->where('id', $order['single_id'])->value('cat_name');

        } else {

            fail('没有扫码订单');

        }

        if($order['is_certification'] != 2){

            //$order['car_number'] = $order['brand_number'] = $order['id_code'] = '';

        }

        if($order['single_parent_id'] == 1 || $order['single_parent_id'] == 2){

            $order['car_number'] = Db::name('order_service')->where('order_id',$order['id'])->value('plat_number');

            $order['brand_number'] = Db::name('order_service')->where('order_id',$order['id'])->value('brand_number');

            $order['id_code'] = Db::name('order_service')->where('order_id',$order['id'])->value('plat_code');

        }

        if ($order['status'] == 10 || $order['status'] == 11 || $order['status'] == 12) {

            $order['refund_create_time'] = Db::name('order_refund')->where('order_id', $order['id'])->value('create_time');

        }

        if ($order['service_type_id'] == 1 || $order['service_type_id'] == 2 || $order['service_type_id'] == 3) { //1保险 2年检

            $order['service_info'] = Db::name('order_service')

                ->where('order_id', $order['id'])

                ->find();

            foreach (explode(',', $order['service_info']['type_id_str']) as $k => $v) {

                $order['service_info']['type_id_name'][] = Db::name('protect_type')->where('id', $v)->value('title');

            }

        }



        //$shop_id = Db::name('shop_create')->where('manage_id',Session::get('manage_id'))->value('shop_id');//当前创建的门店id;

//        if(!empty(\session('shop_id'))){

//             $shop_id =  \session('shop_id');

//        }else{

//            $shop_id =

//        }

        $shop_id = $order['shop_id'];

        $shop_assignor = Db::name('shop_assignor')->where('shop_id',$shop_id)->select();//门店人员

        $shop_assignor_records = Db::name('shop_assignor_records sar')

            ->join('shop_assignor sa', 'sar.assignor_id = sa.id','left')

            ->join('single s','sar.single_id = s.id','left')

            ->where('order_id', $service_order['id'])

            ->field('sar.*,sa.name,s.cat_name')

            ->select();

        $shop_assignor_records = Db::name('shop_assignor_records sar')

            ->join('shop','shop.id = sar.shop_id','left')

            ->join('shop_assignor sa','sar.assignor_id = sa.id','left')

            ->join('single s','sar.single_id = s.id','left')

            ->join('goods_type gt','gt.id = sar.single_id','left')

            ->where('order_id', $service_order['id'])

            ->field('sar.*,shop.shop_title,sa.name,s.cat_name,gt.title')

            ->select()->toArray();

        if(!empty($shop_assignor_records)){

            foreach ($shop_assignor_records as $k => &$v){

                if($v['order_type'] == 2){

                    $v['single_name'] = $v['cat_name'];

                }

                if($v['order_type'] == 1){

                    $v['single_name'] = $v['title'];

                }

                $v['assignor_content'] = Db::name('single')->where('id',$v['assignor_content'])->value('cat_name');

            }

        }

        //退款审核记录

        $refund_order_audit_records = (new RefundOrderAudit())

            ->alias('roa')

            ->join('manager m','roa.manage_id = m.id')

            ->field('roa.*,m.username')

            ->where('order_id',$order['id'])

            ->select();

        //审核会员数量 不管通过不通过;

        $count = (new RefundOrderAudit())->where('order_id',$order['id'])->where('status','11')->count();

        $refund_button = false; //这么判断 其他人员肯定是false

        if($level == 5){

            if($count == 0){

                $refund_button = true;

            }

        }

        if($level == 7){

            if($count == 1){

                $refund_button = true;

            }

        }

        if($level == 8){

            if($count == 2){

                $refund_button = true;

            }

        }

        if($level == 9){

            if($count == 3){

                $refund_button = true;

            }

        }

        if($level == 10){

            if($count == 4){

                $refund_button = true;

            }

        }

        if(\session('auding_status') == 2){

            $where = [];

        }else{

            $where['shop_id'] = ['eq',\session('shop_id')];

        }



        $spec_attr_list = (new \app\console\model\ShopGoods())

            ->alias('sg')

            ->where($where)

            ->join('shop_spec_attr ssa','sg.id = ssa.goods_id')

            ->join('shop s','ssa.shop_id = s.id')

            ->where('ssa.shop_id','eq',$shop_id)

            ->field('sg.title,ssa.*,s.shop_title')

            ->where('s.auding_status',2)

            ->where('s.is_delete',1)

            ->paginate(1000)->each(function ($item, $key){



            });



        $service_order_goods = Db::name('service_order_goods')->where('order_id',$service_order['id'])->select();

        $service_people_price = Db::name('shop_service_price')

            ->alias('ssp')

            ->join('single s','ssp.single_id = s.id','right')

            ->where('shop_id',$shop_id)

            ->where('s.id',$order['single_parent_id'])

            ->where('s.parent_id','eq',0)

            ->where('auding_status',2)

            ->where('is_delete',1)

            ->field('s.id,s.cat_name,ssp.person_price')

            ->select(); //服务人员提成;

        if(session('role_id') != 1){

            $order['username'] = hideStr($order['username'],1,6);

        }



        $service_people_price2 = Db::name('shop_service_price')

            ->alias('ssp')

            ->join('single s','ssp.single_id = s.id','left')

            ->where('shop_id',$shop_id)

            ->where('s.id',$order['single_id'])



            ->field('s.id,s.cat_name,ssp.person_price')

            ->select(); //服务人员提成;

        if($service_people_price2->isEmpty()){

            fail('人员提成或者分类错误');

        }

        $service_people_price2_first = '';

        if(!$service_people_price2->isEmpty()) $service_people_price2_first = $service_people_price2->toArray()[0]['person_price'];

        $template = '';

        if(isset($param['table'])) $template = 'service_order_table';

        return view($template, ['item' => $order,

            'service_people_price2' => json_encode($service_people_price2->toArray()),

            'service_people_price2_first' => $service_people_price2_first,

            'refund' => $refund,

            'service_people_price' => $service_people_price,

            'shop_assignor' => $shop_assignor,

            'shop_assignor_records' => $shop_assignor_records,

            'refund_order_audit_records' => $refund_order_audit_records,

            'refund_button' => $refund_button,

            'spec_attr_list' => json_encode($spec_attr_list->toArray()['data']),

            'category' => json_encode(ClassifyAlias::dimension(Cache::get('goodsType'))),

            'service_order_goods' => $service_order_goods

        ]);

    }

    /**

     * @param $cat_id 分类id

     * @return mixed

     * 服务ajax商品

     */

    public function goods_list($cat_id,$shop_id = 0)

    {

        //$data = Db::name('shop_goods')->where('goods_str', 'like', '%,' . $cat_id . ',%')->select();

        if(\session('auding_status') == 2){

            $where = [];

            if(!empty($shop_id)){

                $where['shop_id'] = ['eq',$shop_id];

            }



        }else{

            $where['shop_id'] = ['eq',\session('shop_id')];

        }

        if(!empty($cat_id)) $where['goods_str'] = ['like','%,' . $cat_id . ',%'];

        $spec_attr_list = (new \app\console\model\ShopGoods())

            ->alias('sg')

            ->where($where)

            ->join('shop_spec_attr ssa','sg.id = ssa.goods_id','right')

            ->join('shop s','s.id = ssa.shop_id')

            ->where('ssa.shop_id','gt',0)

            ->field('sg.title,ssa.*,s.shop_title')

            ->where('s.auding_status',2)

            ->where('s.is_delete',1)

            ->paginate(1000)->each(function ($item, $key){

            });



        return ($spec_attr_list->toArray()['data']);

    }



    /**

     * 当前门店的分类商品

     */

    public function goods_list_create($cat_id,$shop_id)

    {

        //$data = Db::name('shop_goods')->where('goods_str', 'like', '%,' . $cat_id . ',%')->select();

        if(\session('auding_status') == 2){

            $where = [];

            if(!empty($shop_id)){

                $where['ssa.shop_id'] = ['eq',$shop_id];

            }

        }else{

            $where['ssa.shop_id'] = ['eq',\session('shop_id')];

        }



        if(!empty($cat_id)) $where['goods_str'] = ['like','%,' . $cat_id . ',%'];

        $spec_attr_list = (new \app\console\model\ShopGoods())

            ->alias('sg')

            ->where($where)

            ->join('shop_spec_attr ssa','sg.id = ssa.goods_id','right','left')

            ->join('shop s','s.id = ssa.shop_id','left')

            ->where('ssa.shop_id','gt',0)

            ->field('sg.title,ssa.*,s.shop_title')

            ->where('sg.auding_status',2)

            ->where('sg.is_delete',1)

            ->paginate(1000)->each(function ($item, $key){

            });



        return ($spec_attr_list->toArray()['data']);

    }







    /**

     * @return array|mixed|\think\response\View

     * 卷码验证

     */

    public function code()

    {



        $auding_status = Session::get('auding_status');

        if($auding_status == 1){

            $where['o.shop_id'] = ['eq',Db::name('shop_create')->where('manage_id',Session::get('manage_id'))->value('shop_id')];

        }

        $date = date('Y-m-d H:i:s',time()-300);

        $order = \app\console\model\Order::alias('o')

            ->join('member m', 'o.member_id = m.id')

            ->join('single se','o.single_parent_id = se.id','left')

            ->join('shop s', 'o.shop_id = s.id','left')

            ->field('o.*,m.username,s.shop_title,se.cat_name')

            ->where('o.code',2)

            ->whereTime('code_time','>=',$date)

            ->where('o.status',6)

            ->find();

        if($order != null) {

            $order = $order->toArray();

        }else{

            fail('没有扫码订单');

        }



        if(Request::instance()->isPost()){

            $param =  Request::instance()->param();

            if($order['status'] == 1) { //派单

                if($param['shop_id'] > 0 && $param['amount'] > 0){

                    $ret = Db::name('order')->where('id', $order['id'])->update(['amount' => $param['amount'], 'shop_id' => $param['shop_id'],'status' => 6]);

                    if ($ret) {

                        Db::name('member_message')->insert(

                            ['member_id' => $order['member_id'],

                                'order_number' => $order['order_number'],

                                'type_id' => 2,

                                'title' => '您的服务订单已派单,请支付',

                                'content' => $order['order_number'],

                                'is_click' => 1,

                                'create_time' => date('Y-m-d H:i:s',time())

                            ]);



                        win('派单成功', Url::build('index'));

                    }

                }else {

                    fail('派单失败');

                }

            }

        }

        $now_time = time();

        $code_time = strtotime($order['code_time']);

        if($order['code'] == 2 && $now_time - $code_time > 180){ //小于3分钟

            fail('请扫码验证3');

        }

        if($order['status'] == 10 || $order['status'] == 11 || $order['status'] == 12){

            $order['refund_create_time'] = Db::name('order_refund')->where('order_id',$order['id'])->value('create_time');

        }

        if($order['service_type_id'] == 1 || $order['service_type_id'] == 2){ //1保险 2年检

            $order['service_info'] = Db::name('order_service')

                ->where('order_id',$order['id'])

                ->find();

            foreach (explode(',',$order['service_info']['type_id_str']) as $k => $v){

                $order['service_info']['type_id_name'][] = Db::name('protect_type')->where('id',$v)->value('title');

            }

        }

        return view('', ['item' => $order]);



    }





    public function shop_assignor_records($id)

    {

        $shop_assignor_records = Db::name('shop_assignor_records')->find($id);

        if (empty($shop_assignor_records)) return ['code' => 400, 'message' => '此服务人员不存在'];

        $ret = Db::name('shop_assignor_records')->delete($id);

        if ($ret) {

            return ['code' => 200, 'message' => '删除成功'];

        }

        return ['code' => 400, 'message' => '失败'];

    }



    /**

     * @param $id

     * @return array

     * 记录

     */

    public function service_order_goods($id)

    {

        $shop_assignor_records = Db::name('service_order_goods')->where('spec_id', $id)->find();

        if (empty($shop_assignor_records)) return ['code' => 400, 'message' => '此服务人员不存在'];

        $ret = Db::name('service_order_goods')->where('spec_id', $id)->delete();

        if ($ret) {

            return ['code' => 200, 'message' => '删除成功'];

        }

        return ['code' => 400, 'message' => '失败'];

    }



    /**

     * @param $order_id

     * @return array

     * 取走轮胎

     */



    public function take_tyre($order_id)

    {

        $ret = Db::name('order')->where('id', $order_id)->update(['faqi'=>2]);

//        if ($ret !== false) {

//            $data = Db::name('order')->where('id',$order_id)->find();

//            if($data['amount'] == 0){

//                $cont = '免费寄存';

//            }else{

//                $cont = '付费寄存,金额'.number_format($data['amount'],2).'元';

//            }

//

//            $member_id =Db::name('member')->where('username',$data['username'])->value('id');

//            (new \app\index\controller\MemberMessage())->jpushMessage($member_id,'您的轮胎已取走,'.$cont,'寄存区间:'.$data['start_time'].'/'.$data['end_time'],3);

//            return ['code' => 200, 'message' => '轮胎已取走'];

//        }

        return ['code' => 200, 'message' => '门店发起取走审核'];

    }



    /**

     * @return array|mixed|\think\response\View

     * 订单创建服务类

     */

    public function single()

    {
		
		if(session('shop_id') !=''){
			$shop_xx = Db::name('shop')->where('id','=',session('shop_id'))->select();
			$shop_single_type = $shop_xx -> column('single_type');
			$shop_single_type_x=implode(',',$shop_single_type);
			
			$shop_x = Db::name('single')->where('id','in',$shop_single_type_x)->where('parent_id','not in','11,5,6,7,9,10')->select();
			$shop_single_a = $shop_x -> column('parent_id');
			$shop_single_aa=implode(',',$shop_single_a);
			$chaxun_de = $shop_single_type_x.",".$shop_single_aa;
			//var_dump($chaxun_de);
			$single = \app\console\model\Single::order(['sort' => 'asc', 'id' => 'asc'])->where('id','not in','11,5,6,7,9,10')->where('id','in',''.$chaxun_de.'')->select();
			
			//$single = \app\console\model\Single::order(['sort' => 'asc', 'id' => 'asc'])->where('id','not in','11,5,6,7,9,10')->where('id','in',$shop_single_type)->select();
			
			//var_dump($shop_single_aa);
			//var_dump('<br>');
			//var_dump($shop_single_type_x);
		}else{
			$single = \app\console\model\Single::order(['sort' => 'asc', 'id' => 'asc'])->where('id','not in','11,5,6,7,9,10')->select();	
		}
		
		//var_dump($single);
		
		
        $single = getMenuTree($single);

        $param = Request::instance()->param();

        if(Request::instance()->isPost()){

            $member_id = Db::name('member')->where('username',$param['username'])->value('id');

            if(empty($member_id)){

                //$member_id = Db::name('member')->insertGetId(['username' => $param['username'],'password' => sha1('123456')]);

                win('会员未注册,创建订单后自动创建账户',Url::build('create',['single_id' => $param['single_id']]));

            }else{

                win('会员已注册,去创建订单',Url::build('create',['single_id' => $param['single_id']]));

            }

        }

        return view('', ['single_list' => $single]);

    }



    /**

     * @return array|mixed|\think\response\View

     */

    public function single_goods()

    {

        $single = \app\console\model\Single::order(['sort' => 'asc', 'id' => 'asc'])->where('id', 'not in', '11,5,6,7,9,10')->select();

        $single = getMenuTree($single);

        $param = Request::instance()->param();

        if (Request::instance()->isPost()) {

            $member_id = Db::name('member')->where('username', $param['username'])->value('id');

            if (empty($member_id)) {

                //$member_id = Db::name('member')->insertGetId(['username' => $param['username'],'password' => sha1('123456')]);

                win('会员未注册,创建订单后自动创建账户', Url::build('create', ['single_id' => $param['single_id']]));

            } else {

                win('会员已注册,去创建订单', Url::build('create', ['single_id' => $param['single_id']]));

            }

        }

        return view('', ['single_list' => $single, 'goods_type' => ClassifyAlias::dimension(Cache::get('goodsType'))]);

    }



    public function username_car_number($username)

    {



    }



    public function upload($image){

        // 获取表单上传文件 例如上传了001.jpg

        $file = request()->file($image);



        // 移动到框架应用根目录/public/uploads/ 目录下

        if($file){

            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');

            if($info){

                // 成功上传后 获取上传信息

                // 输出 jpg

                 $info->getExtension();

                // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg

                return $info->getSaveName();

                // 输出 42a79759f284b767dfcb2a0197904287.jpg

                echo $info->getFilename();

            }else{

                // 上传失败获取错误信息

                echo $file->getError();

            }

        }

    }

    /**

     * @param int $single_id

     * @param int $shop_id

     * @return array|mixed|\think\response\View

     * 创建订单

     */

    public function create($single_id = 0,$shop_id = 0)

    {



        $param = Request::instance()->param();



        $item = [];

        $order_number = order_number();

        $shop_order_number = shop_order_number($shop_id);



        $parent_id = Db::name('single')->where('id', $single_id)->value('parent_id');



        $parent_title = Db::name('single')->where('id', $parent_id)->value('cat_name');



        $single_title = Db::name('single')->where('id', $single_id)->value('cat_name');

        $shop_title = Db::name('shop')->where('id',$shop_id)->value('shop_title');



        $protect_type = Db::name('protect_type')->order('sort','asc')->select();



        $item['single_title'] = $single_title;

        $item['parent_id'] = $parent_id;

        $item['parent_title'] = $parent_title;

        $item['order_number'] = $order_number;

        $item['shop_title'] = $shop_title;

        $item['username'] = $param['username'];



        if($parent_id == 1){ //保险类

            $service_type_id = 1;

        }elseif ($parent_id == 2){

            $service_type_id = 2; //年检

        }else{

            $service_type_id = 3;

        }



        $shop_assignor = Db::name('shop_assignor')->where('is_delete',1)->select();//门店人员

        $item['member_id'] = Db::name('member')->where('username',$param['username'])->value('id');

        $item['car_number'] = Db::name('member')->where('username',$param['username'])->value('car_number');

        $item['is_certification'] = Db::name('member')->where('username',$param['username'])->value('is_certification');







        if(Request::instance()->isPost()){

            $param = Request::instance()->param();



//            return ['code' => 401 ,'message' => $this->upload() ];

            $car_number = Request::instance()->post('car_number');

            if(isset($car_number) && empty($car_number)){

                return ['code' => 400 ,'message' =>'必须填写车牌号'];

                fail('必须填写车牌号');

            }

            $member_isset = '订单创建成功';

            Db::startTrans();

            try {



                if (empty($param['username'])) {

                    return ['code' => 400 ,'message' =>'请填写用户名'];

                    fail('请填写用户名');

                }

                if ($param['shop_id'] <= 0) {

                    return ['code' => 400 ,'message' =>'请填写派单门店'];

                    fail('请填写派单门店');

                }

                if ($param['order_is_free'] == 2) { //付费

                    if ($param['order_price'] <= 0) {

                        return ['code' => 400 ,'message' =>'请填写正确派单金额'];

                        fail('请填写正确派单金额');

                    }

                    if ($param['bill'] == 1) {

                        if (empty($param['bill_email']) || empty($param['bill_phone']) || empty($param['bill_content'])) {

                            return ['code' => 400 ,'message' =>'发票信息不能为空'];

                            fail('发票信息不能为空');

                        }

                    }

                } else {//免费

                    if (empty($param['assignor_id'])) {

                        //return ['code' => 400 ,'message' =>'免费订单必须添加服务人员'];

                        //fail('免费订单必须添加服务人员');

                    }

                }



                if (!empty($param['assignor_id']) && count($param['assignor_id']) != count(array_unique($param['assignor_id']))) {

                    //fail('服务人员不能重复');

                }



                $sj = Request::instance()->param('sj',0);

                if ($param['order_is_free'] == 2) { //order_is_free =  2付费 加支付方式

                    $amount = [

                        'order_price' => $param['order_price'],

                        'freight' => $param['freight'],

                        'amount' => $param['order_price'] + $param['freight'] + $sj,

                        'sj' => $sj,

                        'status' => 1,

                    ];

                } else { //order_is_free = 1 免费

                    $amount = [

                        'amount' => $param['order_price'] + $param['freight'] + $sj, //以前是0 后来改成 有金额 加个是否是free_order字段默认1不免费 2免费

                        'order_price' => $param['order_price'],

                        'freight' => $param['freight'],

                        'status' => 6,

                        'is_free_order' => 2,

                        'auding_status' => 1

                    ];

                }

                if ($param['shipping'] == 1) { // 1商家配送 2到点自取

                    if (empty($param['shipping_province'])) {

                        return ['code' => 400 ,'message' =>'商家配送请填写地址'];

                        fail('商家配送请填写地址');

                    }

                    $shipping = ['shipping_province' => $param['shipping_province'],

                        'shipping_address' => $param['shipping_address'],

                        'shipping_phone' => $param['shipping_phone'],

                        'shipping_name' => $param['shipping_name'],



                    ];

                } else {

                    $shipping = ['shipping_province' => '',

                        'shipping_address' => '',

                        'shipping_phone' => '',

                        'shipping_name' => ''

                    ];



                }



                $member_id = Db::name('member')->where('username', $param['username'])->value('id');



                if (empty($member_id)) {

                    $member_isset = '用户未注册,系统已注册并创建订单';

                    $member_id = Db::name('member')->insertGetId(['username' => $param['username'], 'password' => sha1('123456'),'create_time' => date('Y-m-d H:i:s',time())]);

                }

                $shipping['finance_order'] = set_finance_order($member_id,$shop_id);

                $shipping['order_online'] = 2;

                $shipping['create_shop_id'] = $shop_id;

                $shipping['explain'] = $param['explain'];

                $shipping['is_read'] = 1;

                $shipping['is_read_shop'] = 1;

                $shipping['member_id'] = $member_id;

                $shipping['username'] = $param['username'];

                $shipping['order_number'] = $order_number;

                $shipping['shop_order_number'] = $shop_order_number;

                $shipping['order_type'] = 2;

                $shipping['service_type_id'] = $service_type_id;

                $shipping['single_id'] = $single_id;

                $shipping['single_title'] = $single_title;

                $shipping['single_parent_id'] = $parent_id;

                $shipping['shop_id'] = $shop_id;

                $shipping['shop_title'] = $shop_title;

                $shipping['create_time'] = date('Y-m-d H:i:s', time());



                if ($param['bill'] == 1) { //是否开发票 默认1开 2不开

                    $bill['bill'] = $param['bill'];

                    $bill['bill_type'] = $param['bill_type'];

                    $bill['bill_header'] = $param['bill_header'];

                    $bill['bill_content'] = $param['bill_content'];

                    $bill['bill_phone'] = $param['bill_phone'];

                    $bill['bill_email'] = $param['bill_email'];

                } else {

                    $bill['bill'] = 2;

                    $bill['bill_type'] = '';

                    $bill['bill_header'] = '';

                    $bill['bill_content'] = '';

                    $bill['bill_phone'] = '';

                    $bill['bill_email'] = '';

                }



                $order_public_data = array_merge($shipping, $bill);

                $data = array_merge($amount, $shipping, $bill);

                $order_id = Db::name('order')->insertGetId($data);//订单创建获取订单ID



                if ($parent_id == 1 || $parent_id == 2) { //保险 年检

//                    return ['code' => 400,'message' => $this->upload('image1')];

//                    $protecter_face = $this->uploadOne('protecter_face');

//                    $protecter_back = $this->uploadOne('protecter_back');

//                    $car_face = $this->uploadOne('car_face');

//                    $car_back = $this->uploadOne('car_back');

                    $protecter_face = $this->uploadOne('image1');

//                    return ['code' => 400,'message' => $this->upload('image1')];

                    $protecter_back = $this->uploadOne('image2');

                    $car_face = $this->uploadOne('image3');

                    $car_back = $this->uploadOne('image4');



                    $service = [

//                        'car_number' => $this->car_number('',$member_id),

                        'order_number' => $order_number,

                        'shop_order_number' => $shop_order_number,

                        'member_id' => $member_id,

                        'username' => $param['username'],

                        'order_id' => $order_id,

                        'protecteder' => $param['protecteder'],

                        'phone' => $param['phone'],

                        'plat_name' => $param['plat_name'],

                        'plat_number' => $param['plat_number'],

                        'plat_code' => $param['plat_code'],

                        'engine_number' => $param['engine_number'],

                        'brand_number' => $param['brand_number'],

                        'register_time' => $param['register_time'],

                        'protecter_face' => $protecter_face,

                        'protecter_back' => $protecter_back,

                        'car_face' => $car_face,

                        'car_back' => $car_back,

                        'create_time' => date('Y年m月d日',strtotime($param['register_time']))

                    ];

                    if ($parent_id == 1) {

                        $type_id_str = implode(',', $param['type_id_str']);

                        $service['type_id_str'] = $type_id_str;

                    }

                    Db::name('order_service')->insert($service);



                }



                if (!empty($param['assignor_id'])) {



                    //$single_id = explode('-',$param['single_id_unique'][0])[0];//门店服务分类 第一个类就代表所有相同的服务类了

                    //$single_title = Db::name('single')->where('id',$single_id)->value('cat_name');//服务类型

                   // $assignor_price = explode('-',$param['single_id_unique'][0])[1];//门店金额

                    // 一对多添加数组

                    $shop_assignor_records = [];

                    for ($i = 0; $i < count($param['assignor_id']); $i++) {

                        $shop_assignor_records[$i]['order_id'] = $order_id;

                        $shop_assignor_records[$i]['assignor_id'] = $param['assignor_id'][$i];

                        $shop_assignor_records[$i]['assignor_price'] = $param['assignor_price'][$i];

                        $shop_assignor_records[$i]['single_id'] = $param['single_id_post'][$i];

                        $shop_assignor_records[$i]['assignor_content'] = $param['assignor_content'][$i];

                        $shop_assignor_records[$i]['create_time'] = date('Y-m-d H:i:s', time());

                        $shop_assignor_records[$i]['shop_id'] = $param['shop_id'];

                        $shop_assignor_records[$i]['order_type'] = 2;

                        $shop_assignor_records[$i]['is_agree'] = 1;

                        //                                    Db::name('shop_assignor_records')->insert(

                        //                                        ['assignor_id' => $param['assignor_id'][$i],

                        //                                         'assignor_price' => $param['assignor_price'][$i],

                        //                                         'order_id' => $service_order['id'],

                        //                                         'order_type' => $service_order['order_type'],

                        //                                         'create_time' => date('Y-m-d H:i:s',time()),

                        //                                         'shop_id' => \session('shop_id')

                        //                                        ]);

                    }



                    Db::name('shop_assignor_records')->insertAll($shop_assignor_records);//订单服务人员 一共3次创建

                    //门店确认不需要推送消息 所以注释了



                }

                if($param['order_is_free'] == 1){

                    $m_content = '您的服务订单已经创建完毕,请查看';

                }else{

                    $m_content = '您的服务订单已经创建完毕,请支付';

                }

                Db::name('member_message')->insert(

                    ['member_id' => $member_id,

                        'order_number' => $order_number,

                        'type_id' => 2,

                        'title' => $m_content,

                        'content' => '服务分类:'.$single_title,

                        'is_click' => 1,

                        'create_time' => date('Y-m-d H:i:s', time())

                    ]);

                (new \app\index\controller\MemberMessage())->jpushMessage((string)$member_id, '您的服务订单已经创建完毕', '服务门店:' . $shop_title, 2);

                if(!empty($param['spec_id']) && !empty($param['number'])){ //服务商品

                    $service_order_goods = [];

                    for ($i=0;$i<count($param['spec_id']);$i++){

                        $auding_status = Session::get('auding_status');

                        if($auding_status == 1){ //1门店

                            $shop_id =  \session('shop_id');

                        }else{

                            $shop_id = Request::instance()->param()['shop_id'][$i];

                        }



                        (new ServiceOrderGoods())->save([

                            'shop_id' => $shop_id,

                            'order_id' => $order_id,

                            'cat_id' => $param['cat_id'][$i],

                            'spec_id' => $param['spec_id'][$i],

                            'number' => $param['number'][$i],

                            'create_time' => date('Y-m-d H:i:s',time())

                        ]);

                        //2019063

                        $inventory = Db::name('shop_spec_attr')->where('id',$param['spec_id'][$i])->setDec('inventory',$param['number'][$i]);

//                                    $service_order_goods['order_id'] = $service_order['id'];

//                                    $service_order_goods['cat_id'] = $service_order['cat_id'];

//                                    $service_order_goods['spec_id'] = $service_order['spec_id'];

//                                    $service_order_goods['number'] = $service_order['number'];

//                                    $service_order_goods['create_time'] = $service_order['create_time'];

                    }

                    //(new ServiceOrderGoods())->saveAll($service_order_goods);

                }

                Db::commit();

            } catch (\Exception $e) {

                Db::rollback();

                return ['code' => 400 ,'message' =>$e->getCode().'|'.$e->getMessage().'|'.$e->getLine()];

                fail($e->getCode().'|'.$e->getMessage().'|'.$e->getLine()).'|'.$e->getTrace();

            }

            return ['code' => 200 ,'message' =>'创建成功'];

            win($param['username'] . ':' . $member_isset, Url::build('index', ['code' => 1]));





        }



        if(\session('auding_status') == 2){

            $where = [];

        }else{

            $where['shop_id'] = ['eq',\session('shop_id')];

        }

        $where['ssa.shop_id'] = ['eq',input('shop_id')];



        $spec_attr_list = (new \app\console\model\ShopGoods())

            ->alias('sg')

            ->where($where)

            ->join('shop_spec_attr ssa','sg.id = ssa.goods_id')

            ->join('shop s','ssa.shop_id = s.id')

            ->where('ssa.shop_id','gt',0)

            ->field('sg.title,ssa.*,s.shop_title')

            ->where('sg.auding_status',2)

            ->where('sg.is_delete',1)

            ->group('ssa.goods_id')

            ->paginate(1000)->each(function ($item, $key){



            });



        $service_people_price = Db::name('shop_service_price')

            ->alias('ssp')

            ->join('single s','ssp.single_id = s.id','right')

            ->where('shop_id',$shop_id)

            ->where('single_id',$parent_id)

            ->field('s.id,s.cat_name,ssp.person_price')

            ->select();



        $service_people_price2 = Db::name('shop_service_price')

            ->alias('ssp')

            ->join('single s','ssp.single_id = s.id','right','left')

            ->where('shop_id',$shop_id)

            ->where('single_id',$single_id)

            ->field('s.id,s.cat_name,ssp.person_price')

            ->select();

        if($service_people_price2->isEmpty()){

            fail('人员金额没有设置,请联系总台');

        }



        $w['shop_id'] = ['eq',$shop_id];

        $w['single_id'] = ['eq',$single_id];

        $amount = Db::name('shop_service_price')->where($w)->value('price');



        return view('',['item' => $item,'shop_assignor_records' => [],

           'service_people_price' => json_encode($service_people_price->toArray()),

            'service_people_price2' => ($service_people_price2),

            'shop_assignor'  => $shop_assignor,

            'amount' => $amount,

            'single_parent_id' => $parent_id,

            'category' => json_encode(ClassifyAlias::dimension(Cache::get('goodsType'))),

            'spec_attr_list' => json_encode($spec_attr_list->toArray()['data']),

            'protect_type' => $protect_type]);

    }



    public function car_number($car_number,$member_id){

        if(empty($car_number)){

            //用于给前台下单使用

            $member_car_number = Db::name('member')->where('id',$member_id)->value('car_number');

            $member_car_list_car_number = Db::name('member_car_list')->where('member_id',$member_id)->column('car_number');

            if(empty($member_car_number)){

                $car_number = '';

            }

            if(!empty($member_car_number)){

                if(empty($member_car_list_car_number)){

                    $car_number = $member_car_number;

                }

            }

            if(!empty($member_car_number) && !empty($member_car_list_car_number)){

                $car_number = $member_car_number.'-'.implode('-',$member_car_list_car_number);

            }

        }

        return $car_number;

    }

    public function get_goods_price($spec_id)

    {

        $goods_id = Db::name('shop_spec_attr')->where('id',$spec_id)->value('goods_id');

//            //$goods_find = Db::name('shop_goods')->where('id',$goods_id)->find();

//            $price = Db::name('shop_spec_attr')->where('id',$param['spec_id'][0])->value('price');

//

//            if($price == 0){

//                $price = Db::name('shop_goods')->where('id', $goods_id)->value('price');

//            }

        // $goods_price += $price*$param['number'][$i];

        // return ['code' => 400 ,'message' =>$price];

        $price = Db::name('shop_spec_attr')->alias('ssa')->join('shop_goods sg', 'ssa.goods_id = sg.id')->where('ssa.id',$spec_id)->value('ssa.price');

        if($price == 0){

            $price = $price = Db::name('shop_goods')->where('id', $goods_id)->value('price');

        }

        return $price;

    }



    public function uploadOne($img = 'picUrl', $type = 'thumb')

    {

        $file = request()->file($img);

        write_log(json_encode($file));

        if (!empty($file)) {



            // 移动到框架应用根目录/public/uploads/ 目录下

            $upload = $file->move(ROOT_PATH . 'public' . DS . 'uploads');



            // halt($upload);

            if ($upload) {



                if ($type == 'thumb') {

                    //图片处理

                    imgDispose('public' . DS . 'uploads' . DS . $upload->getSaveName());

                }



                //返回图片地址

                return 'uploads/' . date('Ymd') . '/' . $upload->getFilename();

            }

            return $file->getError();

        }



        return request()->param($img,'');

    }



    public function inventory($number,$spec_id){

        $inventory = Db::name('shop_spec_attr')->where('id',$spec_id)->value('inventory');

        if($inventory < $number ){

            return ['code' => 400,'message' => '库存不足,请减少库存'];

        }else{

            return ['code' => 200,'message' =>  microtime(true)];

        }

    }



    /**

     * @param $shop_id

     * @return array|mixed|\think\response\View

     * 商品类订单

     */

    public function create_goods($shop_id)

    {

        $param = Request::instance()->param();

        $item = [];

        $order_number = order_number();

        $shop_order_number = shop_order_number($shop_id);

        $shop_title = Db::name('shop')->where('id',$shop_id)->value('shop_title');



        $parentStr = Db::name('goods_type')->where('id',86)->value('parentStr');//61跪下 63

        $parentStr_array = explode(',',$parentStr);

        array_pop($parentStr_array);

        array_shift($parentStr_array);

        $type_title = '';

        foreach ($parentStr_array as $k => $v){

            $type_title .= Db::name('goods_type')->where('id',$v)->value('title').'>>';

        }

        $type_title .= Db::name('goods_type')->where('id',86)->value('title').'>>';

        $item['type_title'] = $type_title;

        $item['order_number'] = $order_number;

        $item['shop_title'] = $shop_title;

        $item['username'] = $param['username'];

        $item['member_id'] = Db::name('member')->where('username',$param['username'])->value('id');

        $item['car_number'] = Db::name('member')->where('username',$param['username'])->value('car_number');

        $item['is_certification'] = Db::name('member')->where('username',$param['username'])->value('is_certification');



        if(Request::instance()->isPost()){





            $car_number = Request::instance()->post('car_number');

            if(isset($car_number) && empty($car_number)){

                return ['code' => 400 ,'message' =>'必须填写车牌号'];

                fail('必须填写车牌号');

            }

            $member_isset = '订单创建成功';

//            $goods_id = Db::name('shop_spec_attr')->where('id',$param['spec_id'][0])->value('goods_id');

//            //$goods_find = Db::name('shop_goods')->where('id',$goods_id)->find();

//            $price = Db::name('shop_spec_attr')->where('id',$param['spec_id'][0])->value('price');

//

//            if($price == 0){

//                $price = Db::name('shop_goods')->where('id', $goods_id)->value('price');

//            }

           // $goods_price += $price*$param['number'][$i];

           // return ['code' => 400 ,'message' =>$price];

            Db::startTrans();

            try {

                if (empty($param['username'])) {

                    return ['code' => 400 ,'message' =>'请填写用户名'];

                    fail('请填写用户名');

                }

                if(!isset($param['number'])){

                    return ['code' => 400 ,'message' =>'请添加商品'];

                    fail('请添加商品');

                }

                if (count($param['spec_id']) != count(array_unique($param['spec_id']))) {

                    return ['code' => 400 ,'message' =>'不能添加重复商品'];

                    fail('不能添加重复商品');

                }

                if (!empty($param['assignor_id']) && count($param['assignor_id']) != count(array_unique($param['assignor_id']))) {

                    //fail('服务人员不能重复');

                }

                if ($param['order_is_free'] == 2) { //付费

//                    if ($param['order_price'] <= 0) {

//                        fail('请填写正确派单金额');

//                    }



                } else { //免费 添加商品

                    /*----*/



                }

                if ($param['bill'] == 1) {

                    if (empty($param['bill_email']) || empty($param['bill_phone']) || empty($param['bill_content'])) {

                        return ['code' => 400 ,'message' =>'发票信息不能为空'];

                        fail('发票信息不能为空');

                    }

                }







                if ($param['shipping'] == 2) { // 1商家配送 2到点自取

                    if (empty($param['shipping_province'])) {

                        return ['code' => 400 ,'message' =>'商家配送请填写地址'];

                        fail('商家配送请填写地址');

                    }

                    $shipping = ['area_info' => $param['shipping_province'],

                        'address' => $param['shipping_address'],

                        'address_phone' => $param['shipping_phone'],

                        'address_name' => $param['shipping_name'],



                    ];

                } else {

                    $shipping = ['area_info' => '',

                        'address' => '',

                        'address_phone' => '',

                        'address_name' => ''

                    ];



                }

//                <div class="form-group">

//                                        <label class="control-label col-md-3 col-sm-3 col-xs-12">收货地址详情：</label>

//                                        <div class="col-md-6 col-sm-6 col-xs-12" style="margin-top: 10px;">

//                    姓　　名：{$item.address_name}<br>

//                手 机 号 ：{$item.address_phone}<br>

//                地　　区：{$item.area_info}<br>

//                详细地址：{$item.address}<br>

//                                        </div>

//                                    </div>

                $member_id = Db::name('member')->where('username', $param['username'])->value('id');

                if (empty($member_id)) {

                    $member_isset = '用户未注册,系统已注册并创建订单';

                    $member_id = Db::name('member')->insertGetId(['username' => $param['username'], 'password' => sha1('123456'),'create_time' => date('Y-m-d H:i:s',time())]);

                }

                $shipping['finance_order'] = set_finance_order($member_id,$shop_id);

                $shipping['order_online'] = 2;

                $shipping['create_shop_id'] = $shop_id;

                $shipping['explain'] = $param['explain'];

                $shipping['is_read'] = 1;

                $shipping['is_read_shop'] = 1;

                $shipping['member_id'] = $member_id;

                $shipping['username'] = $param['username'];

                $shipping['order_number'] = $order_number;

                $shipping['shop_order_number'] = $shop_order_number;

                $shipping['order_type'] = 1;

                $shipping['shop_id'] = $shop_id;

                $shipping['shop_title'] = $shop_title;

                $shipping['create_time'] = date('Y-m-d H:i:s', time());





                if ($param['bill'] == 1) { //是否开发票 默认1开 2不开

                    $bill['bill'] = $param['bill'];

                    $bill['bill_type'] = $param['bill_type'];

                    $bill['bill_header'] = $param['bill_header'];

                    $bill['bill_content'] = $param['bill_content'];

                    $bill['bill_phone'] = $param['bill_phone'];

                    $bill['bill_email'] = $param['bill_email'];

                } else {

                    $bill['bill'] = 2;

                    $bill['bill_type'] = '';

                    $bill['bill_header'] = '';

                    $bill['bill_content'] = '';

                    $bill['bill_phone'] = '';

                    $bill['bill_email'] = '';

                }





                if(!empty($param['spec_id']) && !empty($param['number'])){ //服务商品



                    $amount = 0;

                    $freight = 0;

                    $goods_price = 0;

                    $freight_price = 0;

                    for ($i=0;$i<count($param['spec_id']);$i++){ //数量 $param['count'][$i];



                        $goods_id = Db::name('shop_spec_attr')->where('id',$param['spec_id'][$i])->value('goods_id');

                        //$goods_find = Db::name('shop_goods')->where('id',$goods_id)->find();

                        $price = Db::name('shop_spec_attr')->where('id',$param['spec_id'][$i])->value('price');



                        if($price == 0){

                            $price = Db::name('shop_goods')->where('id', $goods_id)->value('price');

                        }

                        $goods_price += $price*$param['number'][$i];



                       // $freight_price += $goods_find['freight']*$param['number'][$i];



                       // $freight += $goods_find['freight']*$param['number'][$i];



                    }

                    $amount += $goods_price+Request::instance()->param('freight',0);

                    if ($param['order_is_free'] == 2) { //order_is_free =  2付费 加支付方式

                        $order_is_free = [

                            'order_price' => $goods_price,

                            'freight' => Request::instance()->param('freight',0),

                            'amount' => $amount,

                            'status' => 1,

                        ];

                    } else { //order_is_free = 1 免费

                        $order_is_free = [

                            'amount' => $amount,

                            'order_price' => $goods_price,

                            'freight' => 0,

                            'status' => 2,

                            'is_free_order' => 2, //1付费 2免费订单

                            'auding_status' => 1



                        ];

                    }

                }

                $freight_price = Request::instance()->param('freight');

                $order_public_data = array_merge($shipping, $bill);

                $data = array_merge($order_is_free, $shipping, $bill);



                $order_id = Db::name('order')->insertGetId($data);//订单创建获取订单ID



                if (!empty($param['assignor_id'])) {

                    $single_id = explode('-',$param['single_id_unique'][0])[0];//门店服务分类 第一个类就代表所有相同的服务类了

                    $single_title = Db::name('single')->where('id',$single_id)->value('cat_name');//服务类型

                    $assignor_price = explode('-',$param['single_id_unique'][0])[1];//门店金额

                    // 一对多添加数组

                    $shop_assignor_records = [];

                    for ($i = 0; $i < count($param['assignor_id']); $i++) {

                        $shop_assignor_records[$i]['order_id'] = $order_id;

                        $shop_assignor_records[$i]['assignor_id'] = $param['assignor_id'][$i];

                        $shop_assignor_records[$i]['single_id'] = $single_id;

                        $shop_assignor_records[$i]['assignor_price'] = $assignor_price;

                        $shop_assignor_records[$i]['assignor_content'] = $param['assignor_content'][$i];

                        $shop_assignor_records[$i]['create_time'] = date('Y-m-d H:i:s', time());

                        $shop_assignor_records[$i]['shop_id'] = $param['shop_id'];

                        $shop_assignor_records[$i]['order_type'] = 1;

                        $shop_assignor_records[$i]['is_agree'] = 1;

                        //                                    Db::name('shop_assignor_records')->insert(

                        //                                        ['assignor_id' => $param['assignor_id'][$i],

                        //                                         'assignor_price' => $param['assignor_price'][$i],

                        //                                         'order_id' => $service_order['id'],

                        //                                         'order_type' => $service_order['order_type'],

                        //                                         'create_time' => date('Y-m-d H:i:s',time()),

                        //                                         'shop_id' => \session('shop_id')

                        //                                        ]);

                    }



                    Db::name('shop_assignor_records')->insertAll($shop_assignor_records);//订单服务人员 一共3次创建

                    //门店确认不需要推送消息 所以注释了

                }

                if($param['order_is_free'] == 1){

                    $m_content = '您的商品订单已经创建完毕,请查看';

                }else{

                    $m_content = '您的商品订单已经创建完毕,请支付';

                }

//                Db::name('member_message')->insert(

//                    ['member_id' => $member_id,

//                        'order_number' => $order_number,

//                        'type_id' => 1,

//                        'title' => $m_content,

//                        'content' => $m_content,

//                        'is_click' => 1,

//                        'create_time' => date('Y-m-d H:i:s', time())

//                    ]);

                (new \app\index\controller\MemberMessage())->jpushMessage((string)$member_id, '您的商品订单已经创建完毕', '创建门店:' . $shop_title, 1);

                if(!empty($param['spec_id']) && !empty($param['number'])){ //服务商品



                    $amount = 0;

                    $freight = 0;

                    $goods_price = 0;

                    $freight_price = 0;

                    for ($i=0;$i<count($param['spec_id']);$i++){

                        if(empty($param['number'][$i])){

                            return ['code' => 400 ,'message' =>'请选择商品数量'];

                        }

                        $goods_id = Db::name('shop_spec_attr')->where('id',$param['spec_id'][$i])->value('goods_id');

                        $shop_id = Db::name('shop_spec_attr')->where('id',$param['spec_id'][$i])->value('shop_id');

                        $attribute = Db::name('shop_spec_attr')->where('id',$param['spec_id'][$i])->value('attribute');

                        $goods_find = Db::name('shop_goods')->where('id',$goods_id)->find();

                        $goods_price += $goods_find['price']*$param['number'][$i];



                        //$freight_price += $goods_find['freight']*$param['number'][$i];

                        //$freight += $goods_find['freight']*$param['number'][$i];

                        $amount += $goods_price+$freight_price;

//20190603

//                        Db::name('shop_spec_attr')->where(['id' => $param['spec_id'][$i]])->setDec('inventory',$param['number'][$i]);//门店库存

//                        Db::name('shop_goods')->where('id',$goods_id)->setInc('sale_number',$param['number'][$i]);//商品销量

//                        Db::name('shop')->where('id',$shop_id)->setInc('sale_number',$param['number'][$i]);//门店销量

                        //先验证

                        $order_goods = [

                            'member_id' => $member_id,

                            'order_id' => $order_id,

                            'order_number' => $order_number,

                            'shop_order_number' => $shop_order_number,

                            'shop_id' => $shop_id,

                            'goods_id' => $goods_id,

                            'title' => $goods_find['title'],

                            'number' => $param['number'][$i],

                            'attribute' => $attribute,

                            'freight' => $goods_find['freight'],

                            'price' => $goods_find['price'],

                        ];



                        Db::name('order_goods')->insert($order_goods);

                    }

                }

                Db::commit();

            } catch (Exception $e) {

                Db::rollback();

                fail($e->getMessage().'|'.$e->getLine());

            }

            return ['code' => 200 ,'message' =>'成功'];

            win($param['username'] . ':' . $member_isset, Url::build('order/index', ['code' => 1]));





        }



        if(\session('auding_status') == 2){

            $where = [];

        }else{

            $where['shop_id'] = ['eq',\session('shop_id')];

        }

        $where['ssa.shop_id'] = ['eq',input('shop_id')];

        $spec_attr_list = (new \app\console\model\ShopGoods())

            ->alias('sg')

            ->where($where)

            ->join('shop_spec_attr ssa','sg.id = ssa.goods_id')

            ->join('shop s','ssa.shop_id = s.id')

            ->where('ssa.shop_id','eq',$shop_id)

            ->field('sg.title,ssa.*,s.shop_title')

            ->where('sg.auding_status',2)

            ->where('sg.is_delete',1)

            ->paginate(1000)->each(function ($item, $key){



            });

        $shop_assignor = Db::name('shop_assignor')->where('shop_id',$shop_id)->select();//门店人员



        $service_people_price = Db::name('shop_service_price')

            ->alias('ssp')

            ->join('single s','ssp.single_id = s.id','left')

            ->where('shop_id',$shop_id)

            ->where('auding_status',2)

            ->where('is_delete',1)

            ->where('s.parent_id','eq',0)

            ->field('s.id,s.cat_name,ssp.person_price')

            ->select();

        $service_people_price2 = Db::name('single')

            ->where('auding_status',2)

            ->where('is_delete',1)

            ->where('parent_id',1)

            ->select();





        return view('',['item' => $item,'shop_assignor_records' => [],

            'shop_assignor'  => $shop_assignor,

            'service_people_price2' => json_encode($service_people_price2),

            'service_people_price' => $service_people_price,

            'category' => json_encode(ClassifyAlias::dimension(Cache::get('goodsType'))),

            'spec_attr_list' => json_encode($spec_attr_list->toArray()['data']),

         ]);

    }



    public function single_gift()

    {



        $single = \app\console\model\Single::order(['sort' => 'asc', 'id' => 'asc'])->where('id', 'not in', '11,5,6,7,9,10')->select();

        $single = getMenuTree($single);

        $param = Request::instance()->param();

        if (Request::instance()->isPost()) {

            $member_id = Db::name('member')->where('username', $param['username'])->value('id');

            if (empty($member_id)) {

                //$member_id = Db::name('member')->insertGetId(['username' => $param['username'],'password' => sha1('123456')]);

                win('会员未注册,创建订单后自动创建账户', Url::build('create', ['single_id' => $param['single_id']]));

            } else {

                win('会员已注册,去创建订单', Url::build('create', ['single_id' => $param['single_id']]));

            }

        }

        //whereTime('end_time','>',time())->

        $where['start_time'] = ['<=', date('Y-m-d H:i:s', time())];

        $where['end_time'] = ['>=', date('Y-m-d H:i:s', time())];

        $gift_list = (new \app\console\model\Gift())->where($where)->order(['sort' => 'asc','id' => 'desc'])->select();

        $template = '';

        if(isset($param['table'])) $template = 'service_order_table';

        return view($template, ['gift_list' => $gift_list,'single_list' => $single, 'goods_type' => ClassifyAlias::dimension(Cache::get('goodsType'))]);

    }



    public function create_gift($shop_id)

    {

        $param = Request::instance()->param();

        $item = [];

        $order_number = order_number();

        $shop_order_number = shop_order_number($shop_id);

        $shop_title = Db::name('shop')->where('id',$shop_id)->value('shop_title');

        $gift_id = Request::instance()->param('gift_id');

        $parentStr = Db::name('goods_type')->where('id',86)->value('parentStr');//61跪下 63

        $parentStr_array = explode(',',$parentStr);

        array_pop($parentStr_array);

        array_shift($parentStr_array);

        $type_title = '';

        foreach ($parentStr_array as $k => $v){

            $type_title .= Db::name('goods_type')->where('id',$v)->value('title').'>>';

        }

        $type_title .= Db::name('goods_type')->where('id',86)->value('title').'>>';

        $item['type_title'] = $type_title;

        $item['order_number'] = $order_number;

        $item['shop_title'] = $shop_title;

        $item['username'] = $param['username'];

        $item['member_id'] = Db::name('member')->where('username',$param['username'])->value('id');

        //$item['car_number'] = Db::name('member')->where('username',$param['username'])->value('car_number');

        $car_number = (new \app\index\controller\GiftOrder())->car_number('',$item['member_id']);

        if(!empty($car_number)){

            $car_number = explode('-',$car_number);

        }

        $item['car_number'] = $car_number;



        $item['is_certification'] = Db::name('member')->where('username',$param['username'])->value('is_certification');





        if(Request::instance()->isPost()){

            $car_number = Request::instance()->post('car_number');

            if(isset($car_number) && empty($car_number)){

                return ['code' => 400 ,'message' =>'必须填写车牌号'];

                fail('必须填写车牌号');

            }

            $member_isset = '订单创建成功';

            Db::startTrans();

            try {

                if (empty($param['username'])) {

                    return ['code' => 400 ,'message' => '请填写用户名'];

                    fail('请填写用户名');

                }

                if(!isset($param['number'])){

                    //fail('请添加商品');

                }

                if (isset($param['spec_id']) &&count($param['spec_id']) != count(array_unique($param['spec_id']))) {

                    return ['code' => 400 ,'message' => '不能添加重复商品'];

                    fail('不能添加重复商品');

                }

                if (!empty($param['assignor_id']) && count($param['assignor_id']) != count(array_unique($param['assignor_id']))) {

                    //fail('服务人员不能重复');

                }

                if ($param['order_is_free'] == 2) {//付费

//                    if ($param['order_price'] <= 0) {

//                        fail('请填写正确派单金额');

//                    }



                } else { //免费 添加商品

                    /*----*/



                }

                if ($param['bill'] == 1) {

                    if (empty($param['bill_email']) || empty($param['bill_phone']) || empty($param['bill_content'])) {

                        return ['code' => 400 ,'message' => '发票信息不能为空'];

                        fail('发票信息不能为空');

                    }

                }







                if ($param['shipping'] == 2) { // 1商家配送 2到点自取

                    if (empty($param['shipping_province'])) {

                        return ['code' => 400 ,'message' => '商家配送请填写地址'];

                        fail('商家配送请填写地址');

                    }

                    $shipping = ['area_info' => $param['shipping_province'],

                        'address' => $param['shipping_address'],

                        'address_phone' => $param['shipping_phone'],

                        'address_name' => $param['shipping_name'],



                    ];

                } else {

                    $shipping = ['area_info' => '',

                        'address' => '',

                        'address_phone' => '',

                        'address_name' => ''

                    ];



                }



//                <div class="form-group">

//                                        <label class="control-label col-md-3 col-sm-3 col-xs-12">收货地址详情：</label>

//                                        <div class="col-md-6 col-sm-6 col-xs-12" style="margin-top: 10px;">

//                    姓　　名：{$item.address_name}<br>

//                手 机 号 ：{$item.address_phone}<br>

//                地　　区：{$item.area_info}<br>

//                详细地址：{$item.address}<br>

//                                        </div>

//                                    </div>

                $member_id = Db::name('member')->where('username', $param['username'])->value('id');

                if (empty($member_id)) {

                    $member_isset = '用户未注册,系统已注册并创建订单';

                    $member_id = Db::name('member')->insertGetId(['username' => $param['username'], 'password' => sha1('123456'),'create_time' => date('Y-m-d H:i:s',time())]);

                }

                $shipping['car_number'] = $car_number;

                $shipping['finance_order'] = set_finance_order($member_id,$shop_id);

                $shipping['order_online'] = 2;

                $shipping['create_shop_id'] = $shop_id;

                $shipping['explain'] = $param['explain'];

                $shipping['is_read'] = 1;

                $shipping['is_read_shop'] = 1;

                $shipping['member_id'] = $member_id;

                $shipping['username'] = $param['username'];

                $shipping['order_number'] = $order_number;

                $shipping['shop_order_number'] = $shop_order_number;

                $shipping['order_type'] = 3;

                $shipping['shop_id'] = $shop_id;

                $shipping['shop_title'] = $shop_title;

                $shipping['create_time'] = date('Y-m-d H:i:s', time());



                if ($param['bill'] == 1) { //是否开发票 默认1开 2不开

                    $bill['bill'] = $param['bill'];

                    $bill['bill_type'] = $param['bill_type'];

                    $bill['bill_header'] = $param['bill_header'];

                    $bill['bill_content'] = $param['bill_content'];

                    $bill['bill_phone'] = $param['bill_phone'];

                    $bill['bill_email'] = $param['bill_email'];

                } else {

                    $bill['bill'] = 2;

                    $bill['bill_type'] = '';

                    $bill['bill_header'] = '';

                    $bill['bill_content'] = '';

                    $bill['bill_phone'] = '';

                    $bill['bill_email'] = '';

                }



                $amount = $goods_price = Db::name('gift')->where('id', $gift_id)->value('sale_price');

                $get_order_is_free = Request::instance()->param('order_is_free');

                if($get_order_is_free == 1){ //1免费 2付费

                    $get_order_is_free = 6; //订单状态

                    //$amount = 0;

                    $order_is_free = [

                        'order_price' => $goods_price,

                        'freight' => Request::instance()->param('freight',0),

                        'amount' => $amount,

                        'status' => $get_order_is_free,

                        'is_free_order' => 2, //免费

                        'auding_status' => 1

                    ];

                }

                if($get_order_is_free == 2){ //2付费

                    $get_order_is_free = 1;

                    $order_is_free = [

                        'order_price' => $goods_price,

                        'freight' => Request::instance()->param('freight',0),

                        'amount' => $amount,

                        'status' => $get_order_is_free,

                        'is_free_order' => 1

                    ];

                }



                $gift = Db::name('gift')->where('id', $gift_id)->find();

                $gift_data = [

                    'gift_id' => $gift['id'],

                    'gift_title' => $gift['title'],

                    'gift_start_time' => $gift['start_time'],

                    'gift_end_time' => $gift['end_time'],

                    'sale_price' => $gift['sale_price'],

                    'gift_origin_price' => $gift['origin_price'],

                    'day' => $gift['day'],

                    'use_time' => date('Y-m-d H:i:s',time()+$gift['day']*3600*24)

                    ];



                $freight_price = Request::instance()->param('freight');



                //$order_public_data = array_merge($shipping, $bill);



                $data = array_merge($order_is_free, $shipping, $bill,$gift_data);



                $order_id = Db::name('order')->insertGetId($data);//订单创建获取订单ID



                Db::name('gift')->where('id', $gift_id)->setInc('sale_number',1);



                $gift_count_list = Db::name('gift_count')->where('gift_id',$gift_id)->column('single_content,single_id,gift_count,gift_count gift_origin_count,day');

                $arr = ['order_id' => $order_id];

                array_walk($gift_count_list, function (&$value, $key, $arr) {

                    $value['start_time'] = date('Y-m-d H:i:s',time());

                    $value['end_time'] = date('Y-m-d H:i:s',time()+$value['day']*3600*24);

                    $value = array_merge($value, $arr);

                }, $arr);



                $ret = Db::name('order_gift_count')->insertAll($gift_count_list);





                if (!empty($param['assignor_id'])) {

                    //$single_id = explode('-',$param['single_id_unique'][0])[0];//门店服务分类 第一个类就代表所有相同的服务类了

                    $single_title = Db::name('single')->where('id',$param['single_id_unique'][0])->value('cat_name');//服务类型

                    //$assignor_price = explode('-',$param['single_id_unique'][0])[1];//门店金额

                    // 一对多添加数组

                    $shop_assignor_records = [];

                    for ($i = 0; $i < count($param['assignor_id']); $i++) {

                        $shop_assignor_records[$i]['order_id'] = $order_id;

                        $shop_assignor_records[$i]['assignor_id'] = $param['assignor_id'][$i];

                        $shop_assignor_records[$i]['single_id'] = $param['single_id_unique'][$i];

                        $shop_assignor_records[$i]['assignor_price'] = $param['assignor_price'][$i];

                        $shop_assignor_records[$i]['create_time'] = date('Y-m-d H:i:s', time());

                        $shop_assignor_records[$i]['assignor_content'] = $param['assignor_content'][$i];

                        $shop_assignor_records[$i]['shop_id'] = $param['shop_id'];

                        $shop_assignor_records[$i]['order_type'] = 1;

                        $shop_assignor_records[$i]['is_agree'] = 1;

                        //                                    Db::name('shop_assignor_records')->insert(

                        //                                        ['assignor_id' => $param['assignor_id'][$i],

                        //                                         'assignor_price' => $param['assignor_price'][$i],

                        //                                         'order_id' => $service_order['id'],

                        //                                         'order_type' => $service_order['order_type'],

                        //                                         'create_time' => date('Y-m-d H:i:s',time()),

                        //                                         'shop_id' => \session('shop_id')

                        //                                        ]);

                    }



                    Db::name('shop_assignor_records')->insertAll($shop_assignor_records);//订单服务人员 一共3次创建

                    //门店确认不需要推送消息 所以注释了



                }

                if($param['order_is_free'] == 1){

                    $m_content = '您的礼包订单已经创建完毕,请查看';

                }else{

                    $m_content = '您的礼包订单已经创建完毕,请支付';

                }

//                Db::name('member_message')->insert(

//                    ['member_id' => $member_id,

//                        'order_number' => $order_number,

//                        'type_id' => 2,

//                        'title' => $m_content,

//                        'content' => $m_content,

//                        'is_click' => 1,

//                        'create_time' => date('Y-m-d H:i:s', time())

//                    ]);

                (new \app\index\controller\MemberMessage())->jpushMessage((string)$member_id, '您的礼包订单已经创建完毕', '创建门店:' . $shop_title, 1);



                if(!empty($param['spec_id']) && !empty($param['number'])){ //服务商品



                    $amount = 0;

                    $freight = 0;

                    $goods_price = 0;

                    $freight_price = 0;

                    for ($i=0;$i<count($param['spec_id']);$i++){

                        $goods_id = Db::name('shop_spec_attr')->where('id',$param['spec_id'][$i])->value('goods_id');

                        $shop_id = Db::name('shop_spec_attr')->where('id',$param['spec_id'][$i])->value('shop_id');

                        $attribute = Db::name('shop_spec_attr')->where('id',$param['spec_id'][$i])->value('attribute');

                        $goods_find = Db::name('shop_goods')->where('id',$goods_id)->find();

                        $goods_price += $goods_find['price']*$param['number'][$i];



                        //$freight_price += $goods_find['freight']*$param['number'][$i];

                        //$freight += $goods_find['freight']*$param['number'][$i];

                        $amount += $goods_price+$freight_price;

//20190603

//                        Db::name('shop_spec_attr')->where(['id' => $param['spec_id'][$i]])->setDec('inventory',$param['number'][$i]);//门店库存

//                        Db::name('shop_goods')->where('id',$goods_id)->setInc('sale_number',$param['number'][$i]);//商品销量

//                        Db::name('shop')->where('id',$shop_id)->setInc('sale_number',$param['number'][$i]);//门店销量

                        //先验证

                        $order_goods = [

                            'member_id' => $member_id,

                            'order_id' => $order_id,

                            'order_number' => $order_number,

                            'shop_order_number' => $shop_order_number,

                            'shop_id' => $shop_id,

                            'goods_id' => $goods_id,

                            'title' => $goods_find['title'],

                            'number' => $param['number'][$i],

                            'attribute' => $attribute,

                            'freight' => $goods_find['freight'],

                            'price' => $goods_find['price'],

                        ];



                        Db::name('order_goods')->insert($order_goods);

                    }

                }

                Db::commit();

            } catch (Exception $e) {

                Db::rollback();

                return ['code' => 500 ,'message' => $e->getMessage().'|'.$e->getLine()];

                fail($e->getMessage().'|'.$e->getLine());

            }

            return ['code' => 200 ,'message' => '创建成功'];

            win($param['username'] . ':' . $member_isset, Url::build('gift_order/index', ['code' => 1]));





        }



        if(\session('auding_status') == 2){

            $where = [];

        }else{

            $where['shop_id'] = ['eq',\session('shop_id')];

        }

        $where['ssa.shop_id'] = ['eq',input('shop_id')];

        $spec_attr_list = (new \app\console\model\ShopGoods())

            ->alias('sg')

            ->where($where)

            ->join('shop_spec_attr ssa','sg.id = ssa.goods_id')

            ->join('shop s','ssa.shop_id = s.id')

            ->where('ssa.shop_id','gt',0)

            ->field('sg.title,ssa.*,s.shop_title')

            ->where('s.auding_status',2)

            ->where('s.is_delete',1)

            ->paginate(1000)->each(function ($item, $key){



            });

        $shop_assignor = Db::name('shop_assignor')->where('shop_id',$shop_id)->select();//门店人员



        $gift_id = Request::instance()->param('gift_id');

        $gift_list = Db::name('gift')->find($gift_id); //当前礼包

        $gift_list['start_time'] = date('Y-m-d H:i:s',time());

        $gift_list['end_time'] = date('Y-m-d H:i:s',time()+3600*24*$gift_list['day']);

        $cat22 = Db::name('gift_count gc')

            ->join('single','gc.single_id = single.id')

            ->where('gift_id',$gift_id)

            ->select()->toArray();//gift_count.gift_id报错

        foreach ($cat22 as &$v){

            $v['cat_name2'] = db('single')->where('id',$v['single_content'])->value('cat_name');

        }

        $gift_list['list'] =$cat22;

        if(!$gift_list['list']){

            return ['code' => 400 ,'message' => '礼包没有设置服务类'];

            fail('礼包没有设置服务类');

        }

        $gift_list['list_id'] =Db::name('gift_count gc')

            ->join('single','gc.single_id = single.id')

            ->where('gift_id',$gift_id)

            ->column('single.id');//gift_count.gift_id报错



        $service_people_price = Db::name('shop_service_price')

            ->alias('ssp')

            ->join('single s','ssp.single_id = s.id','left')

            ->where('shop_id',$shop_id)

            ->where('s.parent_id','eq',0)

            ->where('s.id','in',$gift_list['list_id'])

            ->field('s.id,s.cat_name,ssp.person_price')

            ->select()->toArray(); //一级服务类



//        $service_people_price2 = Db::name('shop_service_price')

//            ->alias('ssp')

//            ->join('single s','ssp.single_id = s.id','right')

//            ->where('shop_id',$shop_id)

//            ->where('s.parent_id','eq',$gift_list['list_id'][0])

//            ->where('auding_status',2)

//            ->where('is_delete',1)

//            ->field('s.id,s.cat_name,ssp.person_price')

//            ->select(); //服务人员提成;

        $service_people_price2 = Db::name('shop_service_price')

            ->alias('ssp')

            ->join('single s','ssp.single_id = s.id','right')

            ->where('shop_id',$shop_id)

            ->where('s.parent_id','in',$service_people_price[0]['id'])

            ->where('auding_status',2)

            ->where('is_delete',1)

            ->field('s.id,s.cat_name,ssp.person_price')

            ->select(); //服务人员提成;



        return view('',['item' => $item,'shop_assignor_records' => [],

            'shop_assignor'  => $shop_assignor,

            'gift_list' => $gift_list,

            'service_people_price' => \GuzzleHttp\json_encode($service_people_price),

            'service_people_price2' => json_encode($service_people_price2),

            'category' => json_encode(ClassifyAlias::dimension(Cache::get('goodsType'))),

            'spec_attr_list' => json_encode($spec_attr_list->toArray()['data']),

        ]);

    }



    /**

     * 使用优惠券

     */

    public function use_coupon_service($order_id, $member_coupon_id, $member_id)

    {

        $member_coupon = Db::name('member_coupon')->where('id', $member_coupon_id)->find();

        $order = Db::name('order')->where('id|shop_order_number', $order_id)->where('member_id', $member_id)->find();

        $price = $order['amount'] - $member_coupon['minus_price'];

        if ($price <= 0) {

            $price = 0.01;

        }

        $data = [

            'coupon_id' => $member_coupon_id,

            'coupon_title' => $member_coupon['title'],

            'coupon_content' => $member_coupon['content'],

            'coupon_price' => $member_coupon['minus_price'],

            'coupon_totol_price' => $member_coupon['total_price'],

            'amount' => $price

        ];

        $ret = Db::name('order')->where('order_number|id', $order_id)->where('member_id', $member_id)->update($data);

        if ($ret !== false) {

            Db::name('member_coupon')->where('id', $member_coupon_id)->setField('status', 2);

            return ['code' => 200, 'message' => '优惠券选择成功'];

        }

        return ['code' => 0, 'message' => '失败'];

    }













}